14

我想建立一个执行异步工作以返回服务的工厂,然后将该工厂提供给工厂提供者,以便在组件加载时将该服务提供给组件。

但是,当提供程序将 注入 时TestServiceTestComponent运行时的类型是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"
    }
}
4

3 回答 3

4

Angular 似乎无法直接为提供者实现异步工厂功能。

为此,我们需要设置一个新函数并将其交给NgModuleAPP_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 不会延迟初始化

于 2018-03-26T06:25:16.953 回答
0

我有一个 service ConfigService,我想异步加载它:

我的提供者数组app.module.ts

providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: ConfigService.factory,
      deps: [HttpClient, ConfigService],
      multi: true
    }
  ]

异步加载的服务 ( config.service.ts):

import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class ConfigService {
  constructor(private http: HttpClient) {
  }

  async init() {
    // await http request
  }

  static factory(http: HttpClient, configService: ConfigService) {
    return () => configService.init();
  }
}

于 2021-08-19T16:26:25.747 回答
-1

你可以让你的承诺功能是异步的

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: []
};
于 2020-10-25T16:25:06.270 回答