Search code examples
angularangular-servicesangular-componentsget-request

Passing data to component using GET request


How can I pass data retrieved in my service back out to a component every time a new data/URL is passed to it and loop over it with NgFor? I would like to use promises and not observables.

For clarification: Service(A) needs to pass its object to Component(B) every time the data changes and then loop over it with NgFor. Thanks in advance

here's my code:

SERVICE(A)

 receiveEvent(eventId){
   return fetch(eventId).then(res => res.json())
   .then((data:any) => {
     console.log(data);
 });

RECEIVING COMPONENT(B)

 requestEvent(requestUrl){
  this._clientService.receiveEvent(requestUrl)
  }

Solution

  • You can return a promise and resolve in the finally callback:

    service

    fetch(URL: string): Promise < any > {
        return new Promise(resolve => {
            this.http.get(URL)
                .subscribe(response => {
                    console.debug("response = %O", response);
                    // set data locally
                    this.myVariable = data[0]["myVarible"];
                }, error => {
                    console.error(error);
                }, () => {  // finally
                    resolve();
                })
        });
    }
    

    calling component constructor

    this.myService.fetch(URL).then(() => {
        console.log(this.myService.myVariable);
    });
    

    Unless you're using websockets, you will have to poll the database frequently for new data; wrap the calling component constructor's fetch in setInterval