如何在角度 5 中进行同步调用?

新手上路,请多包涵

所以,我试图解决这个问题。但是,不知何故我无法这样做,可能是因为缺乏角度 5 的知识。这是我的服务:

 GetCurrentUserData(): Observable<ResponseData> {
    return this.http.get<ResponseData>(ApplicationURLS.GetCurrentUserInformation)
        .map(response => {
            return response;
        });
    //.catch(error => this.handleError(error));
}

这是我的组件:

 public GetCurrentUserInformation(): any {

        return this.loginService.GetCurrentUserData().subscribe(data => { return data; });
    }

在这里,我正在尝试访问数据:

 ngAfterViewInit() {
        debugger;
        this.responseData = this.GetCurrentUserInformation();
        if (this.responseData.code != responseCodes.success) {
            this.googleInit();
        }

    }

当我检查 this.responseData 它总是返回这个而不是我想要数据: 在此处输入图像描述

我只想进行同步调用,以便立即获取数据。

我也尝试在服务中使用 do() 但它返回的 do() 不是一个函数。

原文由 Just code 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 765
2 个回答

这可以通过使用 async/await 🔥🔥 来简化

public GetCurrentUserInformation(): Promise<any>{
    return this.loginService.GetCurrentUserData().toPromise()
}

ngAfterViewInit

 async ngAfterViewInit() {
        this.responseData = await this.GetCurrentUserInformation(); // 🧙‍♂️
        if (this.responseData.code != responseCodes.success) {
            this.googleInit();
        }
    }

原文由 Muhammed Albarmavi 发布,翻译遵循 CC BY-SA 4.0 许可协议

使调用同步的最佳方法是使用完整的订阅方法。

source$.subscribe({ 下一个:doSomething,错误:doSomethingElse,完成:lol })。

如果我们订阅了一些东西,并且想要在完成这个订阅后做一些操作,那么我们可以完整地编写代码。

详细阅读 https://rxjs.dev/deprecations/subscribe-arguments

原文由 Engineer 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进