【问题标题】:How to use async/await in Angular/Nodejs如何在 Angular/Nodejs 中使用 async/await
【发布时间】:2018-06-13 21:15:15
【问题描述】:

我有一个 Trip 对象:

{  "id": "1",  "country":"UK",  "city": "London"  }

我正在尝试创建一个编辑表单,在该表单中填充来自行程对象的值。我能够填充国家下拉列表(在ngOnInit() 中),并且所选国家/地区绑定到trip.country。但是我无法获取那个国家的城市,因为显然trip 仍然是undefined,而应该通过trip.country 找到那个国家的城市。 (我尝试打印行程,但未定义)

我尝试将 async 与 getTrip() 函数一起使用,但出现以下错误:

错误:(71, 21) TS1055:Type 'void' 在 ES5/ES3 中不是有效的异步函数返回类型,因为它没有引用与 Promise 兼容的构造函数值。

我认为解决方案是某种异步/等待/承诺策略,但我无法掌握它。

export class TripEditorComponent implements OnInit {
  trip;
  countries;
  cities;

ngOnInit() {
    this.getTrip();
    this.countries = this.countryService.getCountries().subscribe(
        data => { this.countries = data;},
        err => console.error(err),
        () => console.log('done loading countries')
    );
    console.log("this trip: ", this.trip) //this is undefined

    this.cities = this.cityService.getCitiesByCountry(this.trip.country).subscribe(
        data => { this.cities = data; },
        err => console.error(err),
        () => console.log('done loading cities') );
     }

getTrip(): void {
    const id = this.route.snapshot.paramMap.get('id');
    if (id) {
      this.tripService.getTrip(id).subscribe(trip => { this.trip = trip;  });
    } else {
      this.trip = new Trip();
    }
  }
}

任何帮助将不胜感激。

【问题讨论】:

    标签: javascript angularjs node.js


    【解决方案1】:

    试试这样的:

    getTrip(): Promise{
        return new Promise((resolve, reject) => {
            const id = this.route.snapshot.paramMap.get('id');
                if (id) {
                    this.tripService.getTrip(id).subscribe(
                    trip => { 
                        this.trip = trip;
                        resolve();
                   },
                   error=>reject(error)
                 );
                }
                else {
                    this.trip = new Trip();
                    resolve();
                }
        })
    }
    

    用法:

    this.getTrip().then(()=>{
        /*your callback here*/
    })
    .catch(error=>{
        /*catch exception here*/
    })
    

    如果您想使用 async/await,请确保您在您的 compilerOptions (tsconfig.json) 字段中的“target”具有“ES6”值

    【讨论】:

    • @ДмитрийНикифоров 谢谢。但是,我刚刚注意到,城市的 json 文件非常庞大,并且无法正确加载。因此,如果我选择名称以字母 >F 开头的国家/地区,则它是未定义的,因为没有加载整个文件。对于名称以 A-F 开头的国家/地区,代码可以正常工作。所以我试图减少与每个国家相关的城市数量。
    猜你喜欢
    • 2018-09-10
    • 2018-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 2021-10-05
    • 2020-02-05
    • 1970-01-01
    相关资源
    最近更新 更多