javascript - 如何在 Angular/Nodejs 中使用异步/等待

标签 javascript angularjs node.js

我有一个 Trip 对象:

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

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

我尝试将异步与 getTrip() 函数一起使用,但我得到的错误是:

Error:(71, 21) TS1055:Type 'void' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value.

我认为解决方案是某种异步/等待/ 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();
    }
  }
}

我们将不胜感激。

最佳答案

尝试这样的事情:

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”值

关于javascript - 如何在 Angular/Nodejs 中使用异步/等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48090217/

相关文章:

javascript - 使用原型(prototype)或内联扩展对象有什么区别?

javascript - 在 on() 中使用 'id name ends with' 进行动态绑定(bind)

javascript - 如何使用 angularjs 查找嵌套的 json 对象?

AngularJS:找到原始数组中过滤值的索引位置

javascript - testcafe 基于浏览器运行不同的测试

javascript - 使用 localStorage 代替 Redux 或 Context API 可以吗?

javascript - 单击 ID 时如何从 Jquery 内部调用 Javascript 函数

mysql - 使用 Node js 和 Angular JS 以及 mysql 数据库

mysql - sails-mysql 没有选择数据库

Node.js - XML 验证