简体   繁体   中英

How to chain 2 Observables with Angular2

I trying to do the following without success. I am trying fire an http request/Observable depending on a previous http request result.

ngOnInit() {
    this._lights.LastChannel(this.hostname).subscribe(data => {
        this.LastChannel = data.Message;
        this.shields = this.LastChannel / 8;
        if (this.LastChannel % 8 != 0){
            this.shields++;
        }
        for(var i=0; i < this.shields; i++){
            console.log(i+1);
            this.shield(i+1)
        }
    });
}
shield(index){
    this._lights.shieldStatus(this.hostname, index)
        .subscribe(data=> {
            console.log(data.Message.split(' '));
            console.log(data.Message)
        })
}

First request runs fine, second one gets fired. Go server responds 200, but browser shows keep pending.

You need the flatMap operator for this

this._lights.LastChannel(this.hostname).flatMap(
  (data) => {
    let params: URLSearchParams = new URLSearchParams();
    params.set('access_token', localStorage.getItem('access_token'));
    return this._lights.shieldStatus(this.hostname, data.messages).map((res: Response) => res.json());
  }
);

@ThierryTempiler answered this question here: Angular 2: Two backend service calls on success of first service

You need to create a third service function that would join both the requests using Observable.forkJoin .

initial (device){
        var obs = this.LastChannel(device).flatMap(
            (data) => {
                return Observable.forkJoin([
                    Observable.of(data),
                    this.shieldStatus(device, data)
                ]);
            }
        );
        return obs;
    }

then I can call it like

ngOnInit() {
    this._lights.initial(this.hostname).subscribe(data=> console.log(data))
}

and this data is an array of both the request's response.

Array[2]
0
:
Object
Message
:
"64"
Time
:
"2016-05-14T09:13:12.416400176-03:00"

1
:
Object
Message
:
"false false false false false true true true"
Time
:
"2016-05-14T09:13:12.797315391-03:00"

:
2
__proto__
:
Array[0]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM