Angular Async Factory Provider

前端 未结 2 2171
故里飘歌
故里飘歌 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

提交回复
热议问题