gpt4 book ai didi

angular - 服务在 APP_INITIALIZER 之后实例化了两次

转载 作者:行者123 更新时间:2023-12-03 22:18:06 26 4
gpt4 key购买 nike

问题是:我需要进行 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() 方法将被调用两次。
为什么即使 Service 被声明为单例并且 providedIn: root 正在被重新实例化?

最佳答案

这样做的原因是,一旦您将 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

为了解决这个问题,你可以懒惰地获取路由器:
export class TestService {

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

constructor(private _http: HttpClient, private injector: Injector ) {
}
}

Forked Stackblitz

关于angular - 服务在 APP_INITIALIZER 之后实例化了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53226116/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com