angular - 如何将 API 请求中的数据设置为变量,以便在另一个 API 调用中使用它?
问题描述
我使用 MSAL 登录应用程序。登录后,我调用 Microsoft Graph API 来获取当前用户的电子邮件,然后我想将其传递给另一个 API。每次我尝试传递这些数据时,它都会出现未定义。
这是我在组件中从 Microsoft 调用 API 的方法。
userEmail: string | undefined;
getProfile(){
this.http.get(GRAPH_ENDPOINT)
.subscribe((profile: ProfileType) => {
this.userEmail = profile.userPrincipalName; //setting userEmail to the returned email address
console.log(this.userEmail); //logging the email address
});
}
然后,在我的组件的ngOnInit
方法中,我写:
ngOnInit(): void {
this.getProfile();
console.log(this.userEmail) //logging the returned email address
}
这个控制台输出
undefined // the console log from ngOnInit from userEmail
test@microsoft.com // console log from http request
这是我一直遇到的错误,找不到解决方法。我希望能够将 userEmail 设置为从 Microsoft Graph API 返回的帐户电子邮件地址,以便我可以在另一个 API 调用中使用它。
解决方案
在这种情况下,理想的解决方案是使用 Rxjs 运算符 'mergeMap' 链接两个 api 调用。
例子:
this.http
.get("https://reqres.in/api/users?page=1")
.pipe(
mergeMap(users =>
this.http.get("https://reqres.in/api/users/" + users["data"][1].id)
)
)
.subscribe(res => (this.user = res));
在上面的示例中,我们从 api 获取用户列表,然后将用户 id 从它传递到第二个 api 以获取用户详细信息。
Stackblitz - https://stackblitz.com/edit/angular-api-call-euz5jq?file=src/app/app.component.ts
推荐阅读
- xml - 如何在 Postman 中使用 SOAP xml 向 Web 服务发送请求?
- android-studio - 如何在 Android Studio 中创建这个设计?
- python - 加密的 PDF 不会写入磁盘
- sql - 如何在 AnyLogic 类中选择内置 AnyLogic 数据库的数据?
- angular - 动态添加css时不会加载css中的角度图像
- c++ - 表达式中出现意外的整数溢出
- perl - 如何在 Perl Tk 中更改标签中的数据?
- python - 在 Bokeh 中的 Tap 事件上更新 DataTable
- excel - 如何过滤列单元格值不属于其他行的值模式的行?
- android - 关于设置编辑文本框文本相对于另一个编辑文本的更改,反之亦然实时更改