angular - http 等待另一个呼叫完成
问题描述
场景:
- 会员和非会员在同一个页面有不同的内容,例如新闻,用户信息
- “记住我”功能可用
- 加载网站时使用服务器检查本地存储中的令牌以验证用户
- 大多数http请求结果会根据登录状态而有所不同
问题:
- 如何在触发所有 http 请求之前等待用户验证?
http.service.ts 示例代码:
private isReady = false;
constructor(private httpClient: HttpClient) {
this.init();
}
// pass local data to check user login status
// check the token, expired date etc.
public init() {
// this.httpClient.post to verify user status
// this.isReady = true;
}
// http get request used in other components
public get(url) {
if (this.isReady) {
return this.httpClient.get<any>(this.apiRoot + url);
} else {
// how to wait for init() is done before return in here?
return this.httpClient.get<any>(this.apiRoot + url);
}
}
沙盒示例在这里
解决方案
你可以这样试试。在应用程序组件中
async ngOnInit() {
await this.http.init(); // wait until init complete
// Then call your other things
}
HttpService.ts
public async init(): Promise<void> {
await this.httpClient
.get<any>(this.apiRoot + "assets/user.json")
.toPromise()
.then(s => {
console.log("init completed");
});
}
这是代码沙箱链接
推荐阅读
- python - ValueError:使用 env://rendezvous 初始化 torch.distributed 时出错:预期环境变量 MASTER_ADDR,但未设置
- azure-functions - Azure 函数中的返回失败
- vuejs2 - 我的 Nuxt Button 组件没有“href”属性
- sql - 无法使用 SQL 插入数字 - 删除整列/数字为空
- mysql - 获取 MySQL 中字符串字段的 SUM
- php - 无法使用 fputcsv() 和 pg_fetch_xxx() 返回的数组获取 csv 文件
- c++ - 嵌套枚举类与否?
- mysql - 如何为每个外键获取 SQL AVG()
- angularjs - angular-ui-router 总是将应用程序附加到 url
- kotlin - 无法在命令行上运行 Kotlin 程序