Angular Async Factory Provider

前端 未结 2 2172
故里飘歌
故里飘歌 2021-02-19 20:11

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 loa

相关标签:
2条回答
  • 2021-02-19 20:31

    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

    0 讨论(0)
  • 2021-02-19 20:41

    you can make your promise function to be async

    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: []
    };
    
    0 讨论(0)
提交回复
热议问题