在 angular 中使用 swichMap 运算符进行嵌套订阅时出错
Getting error while using swichMap operator for nested subscription in angular
我得到的错误是
Argument of type '(data: Object) => Observable<Object> | undefined' is not assignable to parameter of type '(value: Object, index: number) => ObservableInput<any>'.
Type 'Observable<Object> | undefined' is not assignable to type 'ObservableInput<any>'.
Type 'undefined' is not assignable to type 'ObservableInput<any>'
以下是我遇到问题的代码
this.AService.aFunction(this.parms).pipe(take(1) ,switchMap( data => {
if(data){
return this.aService.bDomain(this.parms)
}
})
).subscribe(result =>{
if(result){
open success modal
} else {
open fail modal
}
})
switchMap 需要一个 observable,但你只给它一个 observable if(data){...
。所以所有其他时间它都会失败。
您可以将 switchMap
更新为始终如一的 return 可观察值,或者您可以过滤以仅保留您想要的值并以这种方式忽略不好的 data
。
更新switchMap
this.AService.aFunction(this.parms).pipe(
take(1),
switchMap(data => {
if(!!data){
return this.aService.bDomain(this.parms)
} else {
return EMPTY;
}
})
).subscribe(result => {
if(result){
open success modal
} else {
open fail modal
}
});
过滤不好data
this.AService.aFunction(this.parms).pipe(
take(1),
filter(data => !!data),
switchMap(data => this.aService.bDomain(this.parms))
).subscribe(result => {
if(result){
open success modal
} else {
open fail modal
}
});
我得到的错误是
Argument of type '(data: Object) => Observable<Object> | undefined' is not assignable to parameter of type '(value: Object, index: number) => ObservableInput<any>'.
Type 'Observable<Object> | undefined' is not assignable to type 'ObservableInput<any>'.
Type 'undefined' is not assignable to type 'ObservableInput<any>'
以下是我遇到问题的代码
this.AService.aFunction(this.parms).pipe(take(1) ,switchMap( data => {
if(data){
return this.aService.bDomain(this.parms)
}
})
).subscribe(result =>{
if(result){
open success modal
} else {
open fail modal
}
})
switchMap 需要一个 observable,但你只给它一个 observable if(data){...
。所以所有其他时间它都会失败。
您可以将 switchMap
更新为始终如一的 return 可观察值,或者您可以过滤以仅保留您想要的值并以这种方式忽略不好的 data
。
更新switchMap
this.AService.aFunction(this.parms).pipe(
take(1),
switchMap(data => {
if(!!data){
return this.aService.bDomain(this.parms)
} else {
return EMPTY;
}
})
).subscribe(result => {
if(result){
open success modal
} else {
open fail modal
}
});
过滤不好data
this.AService.aFunction(this.parms).pipe(
take(1),
filter(data => !!data),
switchMap(data => this.aService.bDomain(this.parms))
).subscribe(result => {
if(result){
open success modal
} else {
open fail modal
}
});