Angular异步工厂提供程序 [英] Angular Async Factory Provider
问题描述
我想建立一个工厂,该工厂进行异步工作以返回服务,然后将该工厂提供给工厂提供者,以便在组件加载时将其提供给组件.
I would like to set up a factory that does async work to return a service, and then provide that factory to a factory provider to provide that service to a component when it loads.
但是,当提供程序将TestService
注入到TestComponent
中时,运行时的类型是ZoneAwarePromise
.我需要一种方法,使提供程序在将服务注入组件之前自动等待"诺言.
However, when the provider injects the TestService
into the TestComponent
, the type at runtime is ZoneAwarePromise
. I need a way to have the provider automatically "await" the promise before it injects the service into the component.
服务
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
]
TestComponent
TestComponent
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无法直接为提供程序实现异步工厂功能.
It seems Angular cannot implement the async factory function for the provider directly.
为此,我们需要设置一个新功能并将其移交给NgModule
以执行 APP_INITIALIZER 工作.
In order to do this, we need to set up a new function and hand it over to the NgModule
to do the APP_INITIALIZER job.
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,
},
],
})
另请参见
Angular4 APP_INITIALIZER不会延迟初始化
这篇关于Angular异步工厂提供程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!