问题是:我需要进行 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) {
}
}
但在navigation.component内部,applicationservice又被初始化了。我确信这一点,因为如果我记录或放置调试器语句,服务的 construct() 方法将被调用两次。
为什么即使服务被声明为单例providedIn: root
正在重新实例化吗?
这样做的原因是,一旦你包括Router
依赖于你的APP_INITIALIZER
工厂你得到循环依赖(https://github.com/angular/angular/blob/4c2ce4e8ba4c5ac5ce8754d67bc6603eaad4564a/packages/router/src/router_module.ts#L61-L64 https://github.com/angular/angular/blob/4c2ce4e8ba4c5ac5ce8754d67bc6603eaad4564a/packages/router/src/router_module.ts#L61-L64).
ApplicationService
|
TestService
|
Router
|
ApplicationRef
|
ApplicationInitStatus
|
APP_INITIALIZER
|
ApplicationService
为了解决这个问题,你可以惰性地获取 Router:
export class TestService {
get router() {
return this.injector.get(Router)
}
constructor(private _http: HttpClient, private injector: Injector ) {
}
}
叉式堆栈闪电战 https://stackblitz.com/edit/angular-h5mzak?file=src/app/test.service.ts
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)