我想建立一个执行异步工作以返回服务的工厂,然后将该工厂提供给工厂提供者,以便在组件加载时将该服务提供给组件。
但是,当提供程序将 注入 时TestService
,TestComponent
运行时的类型是ZoneAwarePromise
. 我需要一种方法让提供者在将服务注入组件之前自动“等待”承诺。
服务
export class TestService {
public test() {
return 123;
}
}
供应商和工厂
export function testFactory(auth: any, temp: any) {
return new Promise((res, rej) => {
res(new TestService());
});
}
export let testProvider =
{
provide: TestService,
useFactory: testFactory,
deps: []
};
应用模块
providers: [
testProvider
]
测试组件
import { Component, OnInit } from '@angular/core';
import { TestService } from './Test';
@Component({
selector: 'app-test'
})
export class TestComponent implements OnInit {
constructor(private testService: TestService) { }
async ngOnInit() {
console.log(this.testService.test()); // fails because the type of this.testService at runtime is "ZoneAwarePromise" instead of "TestService"
}
}