URL请求后,Angular订阅Observable [英] Angular Subscribe to Observable after URL request
问题描述
如果我没有为主题和可观察对象使用正确的词汇,请原谅我的行话.
excuse my lingo if I'm not using the correct vocabulary for Subjects and Observables.
无论如何,我想做的是订阅newImages时获得一张图像列表.当前在控制台中,我的答复是
Anyway, what I'd like to do is get a list of images when subscribing to newImages. Currently in the console my response is
[]
[3]
[7]
[9]
其中每个数字都是数组的长度.这是对的.9是正确的长度数组,我正在获取图像列表.
where each number is the length of the array. This is correct. 9 is the correct length array and I'm getting my image list.
但是!我只想将控制台打印出来[9].我不确定为什么要订阅4次.
But! I would just like the console to print out [9]. I'm not sure why I subscribe 4 times.
我如何将订阅延迟到forEach循环完成之前,这样我才不会多次订阅?
How would I delay the subscription until the forEach loop finishes so I'm not subscribing multiple times?
恐怕尝试在HTML组件中显示图像时,我可能会遇到问题.
I'm afraid when trying to display the images in my HTML component I could run into problems.
export class ViewComponent implements OnInit {
constructor(private data: Masterdata) { }
ngOnInit() {
this.data.currentMessage.subscribe(message => this.message = message);
}
getBabies() {
this.data.getBabiesById().subscribe(
data => {
this.BabiesRooms = data;
data.forEach((element) => {
this.data.getImagesByBabyId(String(element.idbabyroom)).subscribe();
});
});
console.log("ASDF");
this.data.newImages.subscribe(data => console.log(data));
}
}
让我改一下它.getBabies()方法中有两个预订.
Let me rephrase it a litte. There are two subscriptions in the method getBabies().
我只希望在第一个订阅完成后调用第二个订阅.
I only want the second subscription to be called after the first subscription is complete.
推荐答案
您可以使用forkjoin来实现:
You can use forkjoin to make that happen:
Observable.forkJoin(
this._myService.makeRequest('Request One', 2000),
this._myService.makeRequest('Request Two', 1000),
this._myService.makeRequest('Request Three', 3000)
)
.subscribe(([res1, res2, res3]) => {
this.propOne = res1;
this.propTwo = res2;
this.propThree = res3;
});
还可以利用Rxjs flatMap进行相同的操作:
Also You can make use of Rxjs flatMap for doing the same:
import { switchMap } from 'rxjs/operators';
getBabies() {
return this.data.getBabiesById().do(response => {
// do something with above response
this.BabiesRooms = response;
}).flatMap(response => {
response.forEach((element) => {
this.data.getImagesByBabyId(String(element.idbabyroom)).subscribe();
});
})
}
这篇关于URL请求后,Angular订阅Observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!