Ash*_*him 9 javascript subscribe angular
我想使用 observable 来同步运行我的代码,我想在从服务器获取图标后返回一个真值,以便我可以使用它。我该怎么做 ?
ngOnInit() {
this.addIcons().subscribe(data=>{
if(data===true)
//do something use the data
});
}
addIcons():Observable<boolean>{
this.Service.getIcons().subscribe(icons => {
return return observableOf(true);
});
return observableOf(false);
}
Run Code Online (Sandbox Code Playgroud)
你的addIcons方法变成:
import { of } from 'rxjs';
import { switchMap } from 'rxjs/operators'
ngOnInit() {
this.addIcons().subscribe(data=>{
if(data===true)
//do something use the data
});
}
addIcons():Observable<boolean>{
return this.Service.getIcons().pipe(
switchMap((response) =>{
// do something with icons response
// based on some condition return true or false
return of(true)
})
)
}
Run Code Online (Sandbox Code Playgroud)
addIcons():Observable<boolean>{
const result = new Subject<boolean>();
this.Service.getIcons().subscribe(icons => {
result.next(true);
result.complete();
},
error => {
result.next(false);
result.complete();
});
return result.asObservable();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38789 次 |
| 最近记录: |