服务在APP_INITIALIZER之后实例化两次

luc*_*nti 2 singleton dependency-injection angular angular6

问题是:我需要进行http调用并存储生成动态路由所需的对象。因此,我正在利用APP_INITIALIZER。

// app.module.ts
import { ApplicationService } from './application.service';


providers: [
  ApplicationService,
  { 
  provide: APP_INITIALIZER, useFactory: appServiceFactory, deps: 
  [Injector, ApplicationService], multi: true 
  },
],

function appServiceFactory(injector: Injector, appService: ApplicationService): Function {
  return () => {
    return appService.loadApplication().then((app: Application) => {
      /custom logic
      });
    });
  };
}


// application.service.ts
@Injectable({
  providedIn: 'root'
})

// navigation.component.ts
import { ApplicationService } from './application.service';

export class NavigationComponent implements OnInit {

    constructor(private _applicationService: ApplicationService) {
  }
Run Code Online (Sandbox Code Playgroud)

}

但是在navigation.component内部,再次初始化applicationservice。我敢肯定,因为如果我记录或放置调试器语句,则该服务的Construct()方法将被调用两次。

为什么即使将Service声明为Singleton并providedIn: root重新实例化?

yur*_*zui 6

这样做的原因是,一旦您将对工厂的Router依赖性包括在内,APP_INITIALIZER就会得到循环依赖性(https://github.com/angular/angular/blob/4c2ce4e8ba4c5ac5ce8754d67bc6603eaad4564a/packages/router/src/router_module.ts#L61-L64)。

ApplicationService
       |
    TestService
       |
     Router
       |
  ApplicationRef
       |
ApplicationInitStatus
       |
 APP_INITIALIZER
       |
ApplicationService
Run Code Online (Sandbox Code Playgroud)

为了解决这个问题,您可以懒惰地获得路由器:

export class TestService {

  get router() {
    return this.injector.get(Router)
  }

  constructor(private _http: HttpClient, private injector: Injector ) {
  }
}
Run Code Online (Sandbox Code Playgroud)

分叉的Stackblitz