URL请求后,Angular订阅Observable

编程入门 行业动态 更新时间:2024-10-25 02:20:56
本文介绍了URL请求后,Angular订阅Observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果我没有为主题和可观察对象使用正确的词汇,请原谅我的行话.

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

本文发布于:2023-11-22 23:31:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619341.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:URL   Angular   Observable

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!