angular - 在 Angular 9 中完成另一个命令后执行一个命令
问题描述
我从Api读取了我所在省份的信息,然后我想从Api获取城市的信息,但是当我想申请城市时,属性状态仍然为空并且这个操作没有完成,我该如何解决我的问题?
export class StateComponent implements OnInit {
constructor(public dialog: MatDialog, private _service: AssessmentServiceService) { }
ngOnInit(): void {
this.flagProgressBar = true;
this._service.getDataStates().subscribe(
(res: IState[]) => {
this.state = res;
}
)
for (const index in this.state) {
this._service.getDataCitys(this.state[index].stateId).subscribe(
(res: ICity[]) => {
for (const indexC in res) {
this.city.push(res[indexC]);
}
}
)
}
}
flagProgressBar: boolean = false;
state: IState[] = [];
city: ICity[] = [];
}
问题 2:ngOnInit 完成后哪个方法开始工作?我想在所有操作完成后更改 flagProgressBar。
解决方案
将第二个订阅添加到第一个订阅中。所以它不会运行,直到第一次回来
this._service.getDataStates().subscribe(
(res: IState[]) => {
this.state = res;
for (const index in this.state) {
this._service.getDataCitys(this.state[index].stateId).subscribe(...)
}
}
对于您的第二个问题,您可以将标志放入第二个订阅中。或者您可以使用在 OnInit 之后运行的另一种方法(例如 ngAfterViewInit())