Angular 角度异步工厂提供程序
我想建立一个工厂,它执行异步工作以返回服务,然后将该工厂提供给工厂提供者,以便在组件加载时将该服务提供给组件 但是,当提供者将Angular 角度异步工厂提供程序,angular,angular-providers,Angular,Angular Providers,我想建立一个工厂,它执行异步工作以返回服务,然后将该工厂提供给工厂提供者,以便在组件加载时将该服务提供给组件 但是,当提供者将TestService注入TestComponent时,运行时的类型是ZoneAwarePromise。我需要一种让提供者在将服务注入组件之前自动“等待”承诺的方法 服务 export class TestService { public test() { return 123; } } 供应商和工厂 export function testFactory(a
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"
}
}
似乎Angular无法直接为提供程序实现异步工厂函数 为此,我们需要设置一个新函数,并将其移交给
NgModule
,以执行APP\u初始化器的工作
import {
APP_INITIALIZER,
} from '@angular/core'
function configFactory(testService: TestService) {
// do the async tasks at here
return () => testService.init()
}
@NgModule({
providers: [
{
provide: APP_INITIALIZER,
useFactory: configFactory,
deps: [TestService],
multi: true,
},
],
})
另见
您可以使promise函数异步
export function testFactory(auth: any, temp: any) {
return new Promise(async(res, rej) => {
const inst = new TestService();
await inst.ngOnInit();
res(inst);
});
}
export let testProvider =
{
provide: TestService,
useFactory: testFactory,
deps: []
};
我有同样的问题。你解决了吗?