【发布时间】:2021-07-07 12:39:35
【问题描述】:
我有一个部门列表,将从 API 链接获取。
当我的 Angular 应用程序加载时(我的意思是在 ngOnInit(): void 调用之后),我想要:
- 我将获取所有部门为
async - 那我就
await给所有部门加载 - 最后,我将第一个部门的 ID 保存在一个变量中
我很困惑我应该把我的等待放在哪里
(注意:我的代码正在运行,API 响应来了,我只停留在等待部分)
这是我尝试了多远:
app.component.ts:
import { Component, OnInit } from '@angular/core';
import { DepartmentModel } from '../../user/models/individual-department.model';
@Component({
selector: 'app-requisition-report-one',
templateUrl: './requisition-report-one.component.html',
styleUrls: ['./requisition-report-one.component.css']
})
export class RequisitionReportOneComponent implements OnInit {
displayIndividualDepartmentList: DepartmentModel[] = [];
currentDisplayDepartment: number = null;
constructor(private userService: UserService) { }
ngOnInit(): void {
this.initializeDepartmentList();
}
initializeDepartmentList() {
this.userService.GetAllIndividualDepartment().subscribe(
async (data: DepartmentModel[]) => {
this.displayIndividualDepartmentList = data;
this.currentDisplayDepartment = await this.displayIndividualDepartmentList[0].department_id;
}
);
}
onShowButtonClick() {
console.log(this.currentDisplayDepartment);
}
}
我的 vscode 给了我这样的警告
'await' has no effect on the type of this expression.ts(80007)
此外,在显示按钮单击时,我得到空值。
我想在awaiting 之后从列表displayIndividualDepartmentList 中获取此变量currentDisplayDepartment 中的第一个部门ID,以便加载列表。
TIA
【问题讨论】:
-
尝试同时删除
async和await。您似乎提供了一个回调函数,因此可能会在数据准备好时调用它。 -
这能回答你的问题吗? How can I `await` on an Rx Observable?
-
@nubinub 是的,我想要这样的东西,谢谢
标签: javascript angular typescript async-await observable