Angular2 - Use value of Observable returning method in another Observable

前端 未结 2 1298
你的背包
你的背包 2020-12-18 01:36

The problem

I dont know how to use the value of the currently returned Observable of getUserHeaders() in my http.get.

Current e

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-18 02:15

    Personally, the solution to my problem was to use BehaviorSubject:

    In service (source of the data):

    private theBoolean: BehaviorSubject;
    
    constructor() {
        this.theBoolean = new BehaviorSubject(false);
    }
    
    public getTheBoolean(): Observable {
        return this.theBoolean.asObservable();
    }
    

    To emit new value of theBoolean do smth like

    public setTheBoolean(newValue: boolean): void {
        this.theBoolean.next(newValue);
    }
    

    In component (user of the data):

    this.theService.getTheBoolean().subscribe(value => console.log(value));
    

    Credit to "pashozator" on Reddit

提交回复
热议问题