Ked*_*upa 7 constants angular angular-dependency-injection
我正在尝试导出一个角度常量,我需要设置一个键,其值将从服务中返回。我尝试使用以下代码:
这是我的user-config.ts文件:
export const USER_CONFIG = {
username: new UserService().getUsername()
}
Run Code Online (Sandbox Code Playgroud)
这是我想以常量注入的UserService文件:
export class UserService{
constructor(someOtherService: SomeOtherService)
getUsername() {
return this.someOtherService.getDetails('some/url')
}
}
Run Code Online (Sandbox Code Playgroud)
我无法解决此问题。需要帮忙。
Angular 中的常量可以使用InjectionToken构造:
export const USER_CONFIG = new InjectionToken('User Configuration', {
factory: () => {
return {
// You can inject the UserService to get the username
username: inject(UserService).getUsername()
}
}
});
Run Code Online (Sandbox Code Playgroud)
由于该常量是一个注入令牌,因此可以将其注入到应用程序的其他部分:
export class AppComponent {
constructor(@Inject(USER_CONFIG) config) {
console.log(config.username)
}
}
Run Code Online (Sandbox Code Playgroud)