如何解决如何等待角度执行服务?
我有代码:
data.service.ts
getDataById(id: number): Observable<Model> {
return this.httpClient.get<Model>(this.api + 'data?id=' + `${id}`);
}
data.component.ts
firstFunc(id) {
this.secoundFunc(id);
console.log('res from service',this.data); // log undefined
//do something with this.data
}
secoundFunc(id) {
this.dataService.getDataById(id).subscribe(res=> {
this.data = res;
})
}
如何等待服务执行?然后继续执行其余代码。 我知道http请求是作为异步操作完成的。我已经使用过,promise,async / await,setTimeout,但是这些都无济于事。
解决方法
无法将异步变量变为同步。您唯一可以做的就是根据订阅中的async变量移动所有语句。
firstFunc(id) {
this.dataService.getDataById(id).subscribe(res=> {
this.data = res;
console.log('res from service',this.data);
//do something with this.data
});
}
如果您需要在多个地方使用this.data
,并且不想每次都触发HTTP调用,则可以使用RxJS ReplaySubject
将响应缓存在服务中,并在组件中使用它。
服务
export class DataService {
private cachedSource = new ReplaySubject<any>(1); // <-- cache last emitted value
public cached$ = this.cachedSource.asObservable();
getDataById(id: number): Observable<Model> {
return this.httpClient.get<Model>(this.api + 'data?id=' + `${id}`).pipe(
tap(res => this.cachedSource.next(res))
);
}
}
组件
export class SampleClass implements OnDestroy {
complete$ = new Subject<any>();
firstFunc(id) {
this.getDataById(id);
this.dataService.cached$.pipe(takeUntil(this.complete$)).subscribe(
res => {
this.data = res;
console.log('res from service',this.data);
//do something with this.data
}
);
}
someOtherFunction() {
this.dataService.cached$.pipe(take(1)).subscribe(
res => { // <-- will emit the last value from the HTTP call
console.log('res from service',res);
//do something with `res`
}
);
}
getDataById(id: number) {
this.dataService.getDataById(id).subscribe(); // <-- pushes response to `this.dataService.cached$`
}
ngOnDestroy() {
this.complete$.next(); // <-- close open subscriptions
}
}
,
您可以对订阅中的数据进行操作。
firstFunc(id) {
this.secoundFunc(id);
}
secoundFunc(id) {
this.dataService.getDataById(id).subscribe(res=> {
this.data = res;
console.log('res from service',this.data);
//do something with this.data
})
}
,
也许您可以尝试回调!
firstFunc(id) {
this.secoundFunc(id,() => {
console.log('res from service',this.data);
//do something with this.data
});
}
secoundFunc(id,callback) {
this.dataService.getDataById(id).subscribe(res=> {
this.data = res;
callback && callback();
})
}
或尝试使用异步功能
async firstFunc(id) {
const result = await this.secoundFunc(id).toPromise();
// if (result ???)
// do sth
}
secoundFunc(id) {
return this.dataService.getDataById(id)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。