我有这样的结构:
export class SomeDerived extends SomeBase implements OnInit{
public async ngOnInit(): Promise<void> {
await super.ngOnInit();
this.getBy(this.x);
}
}
export class SomeBase implements OnInit {
public x: any;
public async ngOnInit(): Promise<void> {
try{
await this.fetch();
}catch(e){}
}
public async fetch(): Promise<void> {
const someId = await this.requestService.fetchId().toPromise().id;
this.x = await this.requestService.fetchX(someId).toPromise();
}
}
好吧,当我运行此代码时,SomeDerived中的this.x是未定义的,因为它不等待在SomeBase中设置super.ngOnInit()结果,并且该过程正在继续。我对异步代码不是很好,请您能帮助我了解为什么会这样吗?
答案 0 :(得分:1)
public async fetch(): Promise<void> {
return new Promise( async (resolve, reject) => {
const someId = await this.requestService.fetchId().toPromise().id;
this.x = await this.requestService.fetchX(someId).toPromise();
resolve();
});
}
您需要返回Promise
,否则不能使用await
答案 1 :(得分:0)
我将创建一个实现ngOnInit方法的基本组件。在此基本组件中,您正在创建另一个方法(例如onComponentCreated),该方法在执行异步方法之后被调用。这样,您的派生类将不会实现OnInit,但会实现您的基类,因此正在执行onComponentCreated。
export class SomeDerived extends SomeBase {
................
public onComponentCreated(): Promise<void> {
........
this.getBy(this.x);
........
}
}
export class SomeBase implements OnInit {
public x: any;
........
public ngOnInit() {
........
this.fetch().subscribe(result => {
this.x = result;
this.onComponentCreated();
});
}
public abstract onComponentCreated();
public async fetch(): Observable<void> {
return new Observable(observer => {
const someId = await this.requestService.fetchId().toPromise().id;
const result = await this.requestService.fetchX(someId).toPromise();
observer.next(result)
});
}
}