Accessing async variable of service

隐身守侯 提交于 2019-12-05 16:11:56

First problem, like pointed out in comments, having your providers array at component level will mean that you have separate instances of services, so it's not shared at all. So remove those!

Also you have race conditions, like also mentioned in comments.

I understand that you want to have subscribers listen to when tweetsData has values. What you need to do, is provide these subscribers with observables What you are doing now:

getTweetsData():Observable<any> {
  return this.tweetsData;
}

returns an array (assumingly), not an observable of an array. You cannot subscribe to a "regular" array.

So what I would do, is to declare an Observable in the service:

import { BehaviorSubject } from 'rxjs/BehaviorSubject';

// don't use 'any', type your data instead
// you can also use a 'Subject' if the subscribers are always listening
private tweetsData = new BehaviorSubject<any>(null);
public tweetsData$ = this.tweetsData.asObservable();

then when you get your data, call next():

searchCall() {
  // ....
  this.http.post(...)
    .subscribe((res) => {
      this.tweetsData.next(res.json().data.statuses)
    });
}

Then you have your subscribers listen to this observable, like:

constructor(private twitterService: TwitterService) {
  twitterService.tweetsData$
    .subscribe(data => {
       this.tweetsData = data;
    });
}

That should do it. Further reading from the docs: https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

what is the type of tweetsData in twitter.service.ts

   getTweetsData():Observable<any> 
    {
    return this.tweetsData;
    } 

Is this function returning a observable ? If this is not an observable , you can return Observable.of(this.tweetsData)

 getTweetsData():Observable<any> {
    return Observable.of(this.tweetsData) ;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!