How to use BehaviourSubjects to share data from API call between components in Angular?

前端 未结 6 607
甜味超标
甜味超标 2021-01-28 22:21

I am currently building an Angular application where I make a request to an api, and I map the repsonse to two different arrays. I can use this data in my app.components.t

6条回答
  •  甜味超标
    2021-01-28 22:46

    To share information between components you can use a behaviorSubject in a service that will be used in your different components.

    The BehaviorSubject has the characteristic that it stores the “current” value, the last value, that needs to be shared with other components.

    Its particularity is:

    • need an initial value

      const subject = new MyBehaviorSubject('initialValue');

    • return the last value of the subject

    • You can retrieve the last value with getValue() method ( non observable)

      subject.getValue()

    • you can subscribe to it:

      subject.subscribe(console.log);

    • update the value with next()

      subject.next('New value');

    I give you an example: in my service:

     private isOpen = new BehaviorSubject(false);
    
       public getNavBarOpen(): Observable {
        return this.isOpen.asObservable();
      }
    
        setNavBarOpen(status: boolean): void {
         this.isOpen.next(status);
      }
    

    in my component:

    if I want to update the value :

    this.myService.setNavBarOpen(true);
    

    If i want to get the value :

    this.myService.getNavBarOpen().subscribe()
    

提交回复
热议问题