pmi*_*nda 7 javascript rxjs typescript
我在Angular应用程序中有以下代码,html看起来像这样。
<ng-multiselect-dropdown
(onSelect)="onSubstringSelect($event)">
</ng-multiselect-dropdown>
Run Code Online (Sandbox Code Playgroud)
那onSubstringSelect
是在组件的.ts部分中:
onSubstringSelect(item: any) {
const dataPois = this.getPois(data);
alert("2nd alert " + dataPois);
// etc
}
Run Code Online (Sandbox Code Playgroud)
getPois(data): any[] {
this.api.getPois(data).subscribe((result: any) => {
alert("1st alert");
return result.pois;
}
}, (error: any) => {
console.error('error', error);
return {};
});
return null;
}
Run Code Online (Sandbox Code Playgroud)
我期望我先拥有alert("1st alert");
,然后再alert("2nd alert " + dataPois);
执行警报。为什么?
这是因为 Rx Streams 是异步的。当您设置流时,它确实会设置它;但除非有东西在听这个,否则什么都不会运行。在 Rx 世界中,这称为subscribing
.
当您将流交给使用者AsyncPipe
时stream$ | async
;它将订阅并且设置流中的所有功能将开始按顺序运行。
乍一看这似乎违反直觉,但实际上很有意义。如果您希望console.log
按照您想要的顺序运行,请按tap()
operators
顺序添加或重新定义您的流以符合您的期望。
当你这样做时:
function A() {
const stream$ = this.http.get('my-stream-url').pipe(
tap(() => { console.log('stream is live!') })
)
console.log('But this will show up first, because nothing is listening to the stream$ yet!')
return stream$
}
Run Code Online (Sandbox Code Playgroud)
您可以看到流将如何保持停滞状态,直到有人开始收听subscribing
。
归档时间: |
|
查看次数: |
76 次 |
最近记录: |