Generating an Asynchronous Observable using an array within a service and displaying the results in the template

I am currently developing a geolocation application, where users' locations are captured and stored in an array called "nearme" using Firebase. The intention is to convert this array into an observable for real-time updates on nearby users in the app's components. However, I seem to be encountering an issue with accessing the array in the outputUsers() function, preventing any data from being passed through. I'm unsure of what the specific problem might be or how to properly make this array asynchronous within the component to enable dynamic updates on users who are close by. Any assistance would be greatly appreciated.

    import { Injectable, NgZone } from '@angular/core';
    import { Geolocation, Geoposition, BackgroundGeolocation } from 'ionic-native';
    import 'rxjs/add/operator/filter';
    import { Fb } from './firebase';
    import 'rxjs/Rx';
    import { Observable } from 'rxjs/Observable';
    import { Observer } from 'rxjs/Observer';
    import { AsyncSubject } from 'rxjs/AsyncSubject';
    import 'rxjs/add/operator/share';
    import 'rxjs/add/operator/map';

    export class Iusers {
    userid: string;
    userdistance: string;
    userloc: string;
    }

    @Injectable()
    export class LocationTracker {

        public usersNearMe$: Observable<Iusers[]>;
        private _usersNearMeObserver: Observer<Iusers[]>;
        private _usersNearMeDataStore: { users: Iusers[] };

        public nearme = <[Iusers]>[];

    constructor(public zone: NgZone, public fire:Fb ) {
            this.usersNearMe$ = new Observable<Iusers[]>(observer => this._usersNearMeObserver = observer).share();                 
            this._usersNearMeDataStore = {  users: [] };
    }


    startTracking( activeUser:any ) :any  {
        ... other actions taking place ....

        geoQuery.on("key_entered", (key, location, distance) => {
            this.nearme.push({ userid: key, userloc: location, userdistance: distance.toFixed(2) });
        });
    }



    outputUsers() {
    this._usersNearMeDataStore.users = this.nearme;
    this._usersNearMeObserver.next(this._usersNearMeDataStore.users);
    }





    }

The Component responsible for presenting this information upon receipt is structured as follows:

        export class OverviewPage {

        public members: FirebaseListObservable<any[]>;
        public activeUser: string;
        public usersNearMe: Observable<any>;

        constructor(  public locationTracker: LocationTracker, public fire: Fb, af: AngularFire,  public appHeaderPopover:AppHeaderPopoverController, public zone: NgZone, public navCtrl: NavController, public navParams: NavParams ) {
                    this.locationTracker.startTracking( this.activeUser );  
                    this.locationTracker.usersNearMe$
                    this.locationTracker.outputUsers();
        }

  ... additional features...

 }

and the corresponding html layout

      <div class="" *ngFor="let item of usersNearMe | async">
        displaying item {{ item.key }}
      </div>

Answer №1

You have only one instance of publishing values from the observer, which is inside <code>outputUsers()
. This happens only once in your code.

It seems like you may want to publish new values when fetching data inside the startTracking() method.

To continuously publish values whenever there are changes, consider adding outputUsers() in the following section:

geoQuery.on("key_entered", (key, location, distance) => {
    this.nearme.push({ userid: key, userloc: location, userdistance: distance.toFixed(2) });
    this.outputUsers();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating through a jQuery array while utilizing the $.inArray method

Below is an example of my Array that I am working with, retrieved from a successful jQuery .post call: data = JSON.parse(data); $(".chk_permission_").each(function() { if ($.inArray($(this).val(), data)) { $(thi ...

Rails - implementing ajax in partials causing an error: 'cannot find method render'

I am encountering an issue with my form partial located within a div that has the id "chapcomments". The form includes a submit button: <%= f.submit "Post", remote: true %> Within the correct view folder, I have a file named create.js.erb which con ...

Utilizing PrimeNG dropdowns within various p-tree nodes: Distinguishing between selected choices

I am working with a PrimeNg p-tree component <p-tree [value]="treeNodes" selectionMode="single" [(selection)]="selectedNode"></p-tree> The treeNodes are defined using ng-templates, with one template looking li ...

Adding Angular directives to the DOM after the document has finished loading does not function properly in conjunction with ngAnimate

I've been working on developing an Angular service that can dynamically append a notification box to the DOM and display it without the need to manually add HTML code or write show/hide logic. This service, named $notify, can be used as follows: $no ...

Try to locate a particular sequence of characters

I am currently on a quest to locate a specific row within the database that corresponds to the message provided by the user, specifically: catalystname. After successfully indexing the given string as text within the schema: const { Schema } = mongoose; ...

Troubleshooting: Why is my Local Image not displaying in ReactJS

I am facing an issue with displaying images in my React application using an array of image paths. Below is the code snippet I have written: import React, { Component } from 'react'; class ItemsList extends Component { constructor() { ...

AngularJS: Understanding the 'controller as' syntax and the importance of $watch

Is it possible to subscribe to property changes when using the controller as syntax? controller('TestCtrl', function ($scope) { this.name = 'Max'; this.changeName = function () { this.name = new Date(); } // not working ...

Can Puppeteer extract the complete HTML content of a webpage, including any shadow roots?

When using Puppeteer to navigate a webpage, I typically can retrieve the full HTML content as text with this code: let htmlContent = await page.evaluate( () => document.querySelector('body').innerHTML ); However, I am currently faced with ...

What is the best way to eliminate additional values depending on the one I have chosen?

When utilizing the Vuetify v-autocomplete component with the multiple prop, we are able to select multiple values. How can I deselect other values based on the value I have selected? For instance: If I choose the main value, all others will be deselecte ...

The TablePagination component from Material Ui is not functioning properly with my specific array of objects

My TablePagination is not updating the rows on each page of my table and not even limiting the rows with the row filter. I suspect this may be due to the way I'm building the table using an array mapping like this: 0: [name: Robert, age: 15, ...

The Proper Method of Displaying Data from a JSON File Using AngularJS

I'm having trouble getting the data from a JSON file (click on the "Json File" link to view the structure). I'm not sure what to put after "$Scope.listOfRecipe=". I tried using response.data.recipes, but it's not working and causing errors. ...

Issue encountered while setting up controls and AbstractControls in form development

Here is a snippet of code showing how I create and manipulate a form in Angular: this.myForm = new FormGroup({ points: new FormArray([ new FormGroup({ date: this.date, startTime: new FormControl(null, Val ...

Issue with Materializecss and Angular Cli: The select component is experiencing a dropdown malfunction

I recently integrated materializecss into my angular-cli project, but I am facing an issue with the select components. Upon clicking them for the first time, they do not behave as expected and only show the content after the second click. https://i.sstati ...

Error: Unable to access attributes of null object (specifically 'disable click')

Currently, I am integrating react-leaflet with nextjs. Within the markers, there are popups containing buttons that open another page upon click. However, I have encountered an error when navigating to the new page: Unhandled Runtime Error TypeError: Canno ...

Retrieve data from external URL using API

I am encountering a captchas page when attempting to retrieve JSON data from a URL through my API. Even though I am trying to access an array of JSON data containing openPrice, highPrice, price, and lowPrice, all I seem to get is a captcha form instead of ...

All you need to know about the impressive world of HTML5

When the server sends coordinates for a shape like a rectangle, rhombus, circle, trapezium, or polygon and I am uncertain about which one will be received, how should I decide on the figure to draw on the canvas using the Angular framework? ...

The global variable remains unchanged within an ajax request

Here is the code I am working with: In developing this code, I referenced information about the window variable from here <script> $(window).on("load", function() { function myForeverFunc(){ ...

Unexpected lack of parameters in a function triggered by an event listener's callback

I am currently working with a functional react component where I am attempting to attach events to multiple elements simultaneously. However, I am encountering issues with passing a trigger element to a function. export default function Header() { cons ...

Are the Angular App routerlinks functioning properly in development but encountering issues in the production environment?

Every time I execute the command npm start, my Angular application works perfectly as intended. However, when I attempt to build it in "prod" mode, my application doesn't seem to function properly. It only displays a static page. All navigation link ...

TypeScript code to transform an array of strings into a custom object

I have a specific requirement that I have partially achieved using Java, but now I need to transition it to TypeScript on the client side. Please note: The input provided below is for illustrative purposes and may vary dynamically. Input: var input = [" ...