英文:
useFactory provider is not being called from my module
问题
我模块的提供者没有被 Angular 调用。我正在使用 Angular 14。
export const FIRE_BASE_AUTH = new InjectionToken<Auth>('FIRE_BASE_AUTH');
function getFirebaseAuth() {
console.log('getFirebaseAuth called...'); // 这不会显示在控制台中
return LoginSpaModule.firebaseAuth;
}
@NgModule({
declarations: [
LoginComponent
],
imports: [
// ...
],
providers: [
{ provide: FIRE_BASE_AUTH, useFactory: getFirebaseAuth }
],
exports: [LoginComponent]
})
export class LoginSpaModule {
static firebaseAuth: Auth;
constructor() {
console.log('we are in the LoginSpaModule constructor...', LoginSpaModule.firebaseAuth); // 这在控制台中显示
}
}
以及我的组件:
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
constructor(
@Inject('FIRE_BASE_AUTH') private auth: Auth,
private router: Router
) { }
// ...
}
如果我尝试将 FIRE_BASE_AUTH
注入到组件中,我会得到 NullInjectorError: No provider for FIRE_BASE_AUTH!
。如果我尝试其他 provide
方法,比如 useValue
,也会出现这个错误。
英文:
The provider for my module is not being called by Angular. I'm using Angular 14.
export const FIRE_BASE_AUTH = new InjectionToken<Auth>('FIRE_BASE_AUTH');
function getFirebaseAuth() {
console.log('getFirebaseAuth called...'); // This is not showing up in the console
return LoginSpaModule.firebaseAuth;
}
@NgModule({
declarations: [
LoginComponent
],
imports: [
...
],
providers: [
{ provide: FIRE_BASE_AUTH, useFactory: getFirebaseAuth }
],
exports: [LoginComponent]
})
export class LoginSpaModule {
static firebaseAuth: Auth;
constructor() {
console.log('we are in the LoginSpaModule constructor...', LoginSpaModule.firebaseAuth); // This is in the console
}
}
And my component:
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
constructor(
@Inject('FIRE_BASE_AUTH') private auth: Auth,
private router: Router
) { }
...
If I try to inject the FIRE_BASE_AUTH
into a component, I get NullInjectorError: No provider for FIRE_BASE_AUTH!
. I get this also if I try other provide
method like useValue
.
答案1
得分: 1
以下是翻译好的部分:
The string would work as the provider if its a string in the @Inject as well.
{ provide: 'FIRE_BASE_AUTH', ... }
constructor(@Inject('FIRE_BASE_AUTH') ...) { }
The token is not being used in this case.
英文:
The string would work as the provider if its a string in the @Inject as well.
{ provide: 'FIRE_BASE_AUTH', ... }
constructor(@Inject('FIRE_BASE_AUTH') ...) { }
The token is not being used in this case.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论