0

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)
  }
Jamal
  • 21
  • 9
  • 1
    I assume you weren't happy with my answer using observables to the last time you asked this question: https://stackoverflow.com/a/60139675/5367916. Can I ask why you don't want to use observables? They really do fit your use case very well. – Kurt Hamilton Feb 09 '20 at 20:21
  • If you insist on promises, then take the advice from my answer to your previous question and look up pub/sub using promises. The pattern is probably more important to you finding a solution here than the technology is. – Kurt Hamilton Feb 09 '20 at 20:30
  • I was struggling to get it to work, I wanted to try a different approach with promises. Observables are a big learning curve for me. – Jamal Feb 09 '20 at 20:38
  • I understand that observables are hard to learn. This is a fairly complex usage of them. I would recommend learning about them though, as they come up all the time as you use Angular more. Start off small by just creating your own subject and experimenting with it. – Kurt Hamilton Feb 09 '20 at 20:42

1 Answers1

0

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

xinthose
  • 3,213
  • 3
  • 40
  • 59