Angular Async Factory Provider

∥☆過路亽.° 提交于 2019-12-09 15:39:55

问题


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.

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.

Service

export class TestService {
 public test() {
   return 123;
 }
}

Provider and Factory

export function testFactory(auth: any, temp: any) {
  return new Promise((res, rej) => {
    res(new TestService());
  });
}

export let testProvider =
{
  provide: TestService,
  useFactory: testFactory,
  deps: []
};

App Module

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

回答1:


It seems Angular cannot implement the async factory function for the provider directly.

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,
    },
  ],
})

See Also

Angular4 APP_INITIALIZER won't delay initialization



来源:https://stackoverflow.com/questions/46257184/angular-async-factory-provider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!