如何从数据库中获取信息并在ngAfterViewInit中使用它们?

时间:2019-11-11 20:43:18

标签: javascript angular

目标是一旦用户按下Enter键,它将提交一个表单,从后端获取信息,并在Angular的ngAfterViewInit()中使用它。 例如,用户输入“蒙特利尔”并提交表格,则数据库中的信息将为

{
  id: 'montreal',
  title: 'Montreal',
  latitude: 45.508888,
  longitude: -73.561668,
  destinationCities: []
}


数据库连接正常。输入城市名称时,我的状态码为200。以下代码片段是我所做的,但未能成功达到目标。截至目前,我有: HTML文件:

<mat-form-field>
  <form [formGroup]="originCityForm" (ngSubmit)="getOriginCity(originCityForm)">
    <input
      matInput
      type="text"
      placeholder="Origin city"
      formControlName="origin"
    />
  </form>
</mat-form-field>


TypeScript文件:

originCity: City;
  getOriginCity(originCityForm: FormGroup) {
    this.service.getCity(originCityForm.value.origin).subscribe(
      city => {
        this.originCity.id = city.id;
        this.originCity.title = city.title;
        this.originCity.latitude = city.latitude;
        this.originCity.longitude = city.longitude;
        this.originCity.destination = city.destination;
      },
      error => console.log(error)
    );
    console.log(this.originCity); // originCity is the user's input as expected. It prints what I expect.
    originCityForm.reset();
  }

但是,由于未定义originCity,因此无法在ngAfterViewInit中重用originCity。

ngAfterViewInit() {
    this.zone.runOutsideAngular(() => {
    // It should be this.originCity.id = 'montreal',
    // It should be this.originCity.title = 'Montreal',
    // It should be this.originCity.latitude = 45.508888,
    // It should be this.originCity.longitude = -73.561668,
    // It should be this.originCity.destinationCity = null,
[...]
}


服务文件(从数据库中获取信息):

  getCity(title: string) {
    return this.http.get<City>(this.baseUrl + '/api/' + title);
  }


0 个答案:

没有答案