How to implement behavior subject using service in Angular 8

后端 未结 4 697
借酒劲吻你
借酒劲吻你 2021-01-02 06:32

I\'m new to Angular and I\'m having an issue.

I\'m creating an app with several sibling components. When I update a value in one component other components don\'t u

4条回答
  •  耶瑟儿~
    2021-01-02 07:07

    There are a few ways to do that. One of them is described here.

    1) Build your service like this:

    // ReplaySubject is more flexible than BehaviorSubject, as it
    // allows you to define how many past emissions should be available.
    // But you can get an equivalent code with BehaviorSubject by
    // coding like this:
    // private _coachProfile$: BehaviorSubject = 
    //    new BehaviorSubject(null);
    private _coachProfile$: ReplaySubject = new ReplaySubject(1);
    
    coachProfile(token :string)
    {  
      return this.http.post(this.apiURL+'/coach/profile_infos',{
        token: token,
      }).subscribe((profile) => this._coachProfile$.next(profile));        
    }
    
    subscribeToGetCoachProfile$()
    {  
      return this._coachProfile$.asObservable();       
    }
    

    2) And in your components:

    ngOnInit() {
      this.coachService.subscribeToGetCoachProfile$()
        .subscribe((profile) => this.coachProfile = profile);
    }
    

    Well there are other approaches you can think of, but I think this is the simpler one given the sample code you pasted on your question.

    As a side note: if you do some search on stackoverflow, you'll see that this question (or similar questions) has been asked many times here. Take a look, for example in this other approach: Multiple subscriptions without recalculate common part

提交回复
热议问题