Javascript 从嵌套回调函数内部返回可观察的
下午好 我目前正在Angular2/4中开发一个web应用程序,我在观察方面有一个问题。目标是在组件内部调用函数,当函数完成时,我希望执行一些代码。因此,“myComp.component.ts”文件中的代码是:Javascript 从嵌套回调函数内部返回可观察的,javascript,angular,observable,Javascript,Angular,Observable,下午好 我目前正在Angular2/4中开发一个web应用程序,我在观察方面有一个问题。目标是在组件内部调用函数,当函数完成时,我希望执行一些代码。因此,“myComp.component.ts”文件中的代码是: this.myService.myFunc1().subscribe(() => { // this code has to be executed after myFunc1() finishes. }); 问题出在“myService.service.ts”文件的“
this.myService.myFunc1().subscribe(() => {
// this code has to be executed after myFunc1() finishes.
});
问题出在“myService.service.ts”文件的“myFunc1()”函数中。该功能的结构如下所示:
可观察的
,其中Status对象就是{Status:'ok'}
李>
{status:'ok'}
返回到“myComp.component.ts”中,以便执行subscribe()中的其他代码myFunc1(): Observable<Status> {
// some code and then call of myFunc2()
this.myService2.myFunc2().subscribe(data => {
// do some staff here and then call of myFunc3()
this.myService3.myFunc3().subscribe(data2 => {
// do some other staff and then call of myFunc4()
this.myService4.myFunc4().subscribe(data3 => {
// do staff and then return program flow into the Component
return Observable.of<Status>({status: 'ok'});
});
});
});
}
myFunc1():可观察{
//一些代码,然后调用myFunc2()
this.myService2.myFunc2().subscribe(数据=>{
//在这里做一些工作,然后调用myFunc3()
this.myService3.myFunc3().subscribe(数据2=>{
//做一些其他工作人员,然后调用myFunc4()
this.myService4.myFunc4().subscribe(数据3=>{
//请确定人员,然后将程序流返回到组件中
返回({status:'ok'})的可观察值;
});
});
});
}
当然({status:'ok'})的返回Observable.of代码>不起作用。我一直在互联网上寻找解决方案和其他Stackoverflow问题的方法,我发现了一些建议,如使用flatMap()、mergeMap()、switchMap()等。我认为这些解决方案不能用于我的情况,因为每个函数都必须一个接一个地执行
我能做什么?我错过了什么?提前感谢您的帮助和时间 您要找的是switchMap或mergeMap。切换映射更好,如果出现新的请求,它将取消以前的请求
myFunc1(): Observable<Status> {
// some code and then call of myFunc2()
return this.myService2.myFunc2()
.switchMap(data => {
// do some staff here and then call of myFunc3()
return this.myService3.myFunc3()
}).switchMap(data2 => {
// do some other staff and then call of myFunc4()
return this.myService4.myFunc4()
}).switchMap(data3 => {
// do staff and then return program flow into the Component
return Observable.of<Status>({status: 'ok'});
});
});
});
}
myFunc1():可观察{
//一些代码,然后调用myFunc2()
返回这个.myService2.myFunc2()
.switchMap(数据=>{
//在这里做一些工作,然后调用myFunc3()
返回这个.myService3.myFunc3()
}).switchMap(数据2=>{
//做一些其他工作人员,然后调用myFunc4()
返回这个.myService4.myFunc4()
}).switchMap(数据3=>{
//请确定人员,然后将程序流返回到组件中
返回({status:'ok'})的可观察值;
});
});
});
}
您可以尝试使用或根据需要组合多个观察者!首先,函数中没有返回任何内容,因此它不会编译。其次,即使您在本例中返回了“subscribe”,也会返回一个订阅,而不是一个可观察的。使用switchMap是链接的正确方法。确保在调用该方法时返回并订阅该方法。它是有效的。它还需要导入'rxjs/add/operator/switchMap'代码>。非常感谢你!