How to share data between components using service and observable?

十年热恋 提交于 2019-12-06 11:12:29
Eliseo

User3511041, only if you subscribe to a Observable, the observable is executed. In a service we can use three approaches. (I use httpClient, not the "old" and "deprecated" http)

@Injectable()
export class PostsService {

  response: any = {};
  private messageResponse = new BehaviorSubject(this.response);
  currentResponse = this.messageResponse.asObservable();

  constructor(private httpClient: Http) { }

  // 1.-Return and observable 
  getAllPosts():Observable<any> {  //see that using httpClient we needn't json()
    return this.http.get('/api/posts').catch(err => {
         console.log('caught exception' + err.status);
         return Observable.throw(err);
      });

  // 2.- using next or  3.-fill an variable
  fillAllPosts():void {  
    this.http.get('/api/posts').catch(err => {
         console.log('caught exception' + err.status);
    }).subscribe(res=>{
          this.messsageResponse.next(res);  //<--(the 2nd approach)
          this.post=res;  //<--or using a variable (for the 3re approach)
    })
}

In a component you can subscribe to a getAllPost() or to current Response

ngOnInit() {

    //1.-Subscribe to a currentResponse
    this.postsService.currentResponse.subscribe(posts => {
      this.posts = posts;
      console.log(this.posts);
    });
    // in this case we must call to fillAllPost after subscription
    this.postService.fillAllPost();

    //2.-Subscribe to a getAllPost()
    this.postsService.getAllPost().subscribe(posts => {
      this.posts = posts;
      console.log(this.posts);
    });
  }

the 3re approach is using a getter

  //a 3re approach is using a getter
  get post()
  { 
       return this.postService.post;
  }
  ngOnInit() {
       this.postService.fillAllPost()
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!