在Angular 9中完成另一条命令后执行一条命令

时间:2020-10-29 04:06:31

标签: angular typescript

我从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。

1 个答案:

答案 0 :(得分:1)

将第二个订阅添加到第一个订阅中。所以它不会运行,直到第一次回来

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())