在 Angular Typescript 中调用异步方法

发布于 2025-01-19 19:31:15 字数 461 浏览 2 评论 0原文

我们对 Angular 很陌生,几乎没有什么方法需要按顺序调用并返回一个值。这里的返回是在执行完成之前调用。我尝试过不同的东西,比如 async wait、promise、setTimeout 但没有运气。有没有任何解决方案可以以角度同步顺序进行此操作

transform(input:any)
{

    this.getCachedUsers(); // this will set the this.CachedUsers array using a http get call(subscribe)
    this.getUserFromCachedUsers(input); // this will set the this.userName based on input userId from this.CachedUsers
    return this.userName; // here its returning empty
}

We are new to angular and we are having few methods needs to be invoked in sequence and return a value. Here the return is invoking before completing the execution. I have tried different things like async await, promise, setTimeout but no luck. Is there any solution to work this in sync order in angular

transform(input:any)
{

    this.getCachedUsers(); // this will set the this.CachedUsers array using a http get call(subscribe)
    this.getUserFromCachedUsers(input); // this will set the this.userName based on input userId from this.CachedUsers
    return this.userName; // here its returning empty
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深海里的那抹蓝 2025-01-26 19:31:15

您应该尝试使用可观察的平面运算符。

为了在完成前一个 Observable 后将 Observable 发出的项转换为另一个 Observable,您可能需要使用 concatMap 运算符。它创建一个内部 Observable 并将其结果平铺到外部流。

const source = this.getCachedUsers()
    .pipe(
        concatMap(result => this.getUserFromCachedUsers(result.userId))
     )
    .subscribe(result2 => {
        // do some stuff
    });

以下是您可以使用的一些表现不同的平面运算符:

  • flatMap/mergeMap - 立即为任何源创建一个 Observable
    item,所有之前的 Observables 都保持活动状态

  • concatMap - 等待之前的 Observable 完成
    创建下一个

  • switchMap - 对于任何源项目,完成前一个 Observable
    并立即创建下一个

  • exhaustMap - 映射到内部可观察值,忽略其他值,直到该值为止
    可观察完成

You should try using observable flat operators.

For transforming items emitted by an Observable into another Observable after completion of the previous observable, you probably want to use the concatMap operator. It creates an inner Observable and flats its result to the outer stream.

const source = this.getCachedUsers()
    .pipe(
        concatMap(result => this.getUserFromCachedUsers(result.userId))
     )
    .subscribe(result2 => {
        // do some stuff
    });

Here are some flat operators you can use that behave differently:

  • flatMap/mergeMap - creates an Observable immediately for any source
    item, all previous Observables are kept alive

  • concatMap - waits for the previous Observable to complete before
    creating the next one

  • switchMap - for any source item, completes the previous Observable
    and immediately creates the next one

  • exhaustMap - map to inner observable, ignore other values until that
    observable completes

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文