Reputation: 7758
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.
Upvotes: 1
Views: 1025
Reputation: 7758
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]
Upvotes: 1
Reputation: 40647
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
Upvotes: 1