TypeScript 和 Angular,这里的执行顺序

我在 Angular 应用程序中有以下代码,html 看起来像这样。


<ng-multiselect-dropdown

    (onSelect)="onSubstringSelect($event)">

</ng-multiselect-dropdown>

那onSubstringSelect是在组件的 .ts 部分:


onSubstringSelect(item: any) {

    const dataPois = this.getPois(data);

    alert("2nd alert " + dataPois);

    // etc

}

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;

}

我期待我首先拥有alert("1st alert");然后alert("2nd alert " + dataPois); 但是该警报首先执行。为什么?


狐的传说
浏览 300回答 2
2回答

当年话下

这是因为 Rx Streams 是异步的。当你设置你的流时,它确实设置了它;但是直到有什么东西在听这个之前什么都不会运行。在 Rx 世界中,这称为subscribing.当您将流交给AsyncPipeusing 时stream$ | async;它将订阅并且设置流中的所有功能将开始按顺序运行。这乍一看似乎违反直觉,但实际上很有意义。如果您希望console.log按照您希望的顺序运行,请按顺序添加tap() operators或重新定义您的流以符合您的期望。当你这样做时:function A() {&nbsp; &nbsp; const stream$ = this.http.get('my-stream-url').pipe(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tap(() => { console.log('stream is live!') })&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; console.log('But this will show up first, because nothing is listening to the stream$ yet!')&nbsp; &nbsp; return stream$}您可以看到流将如何保持停滞,直到有人开始收听subscribing.

慕哥6287543

你不知道什么时候会返回异步数据。在这种情况下,答案是在执行之后alert("2nd alert " + dataPois);。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript