角度异步工厂提供商

时间:2017-09-16 18:32:55

标签: angular angular-providers

我想设置一个工厂来执行异步工作以返回服务,然后将该工厂提供给工厂提供商,以便在加载时为该组件提供该服务。

但是,当提供程序将TestService注入TestComponent时,运行时的类型为ZoneAwarePromise。我需要一种方法让提供程序在将服务注入组件之前自动“等待”promise。

服务

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

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"
    }
}

2 个答案:

答案 0 :(得分:1)

似乎Angular无法直接为提供程序实现异步工厂函数。

为了做到这一点,我们需要设置一个新功能并将其交给NgModule来执行 APP_INITIALIZER 作业。

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 won't delay initialization

答案 1 :(得分:0)

您可以使您的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: []
};