Angular NullInjectorError:没有针对带有Injector的xxx的提供程序
我有以下服务:Angular NullInjectorError:没有针对带有Injector的xxx的提供程序,angular,angular-services,Angular,Angular Services,我有以下服务: @Injectable() export class StudentService { constructor() { } getDataFormStudentService() { return "Hi, I'm Mix"; } } 现在,我想在app.components.ts中使用上面的服务: title = ''; public studentService: StudentService; constructo
@Injectable()
export class StudentService {
constructor() { }
getDataFormStudentService() {
return "Hi, I'm Mix";
}
}
现在,我想在app.components.ts
中使用上面的服务:
title = '';
public studentService: StudentService;
constructor(
private injector: Injector) {
this.studentService = this.injector.get(StudentService);
}
ngOnInit(): void {
this.title = this.studentService.getDataFormStudentService();
}
当我运行项目时,出现以下错误:
错误NullInjectorError:R3InjectorError(AppModule)[StudentService->
StudentService->StudentService]:NullInjector错误:无提供程序
为学生服务
您应该在获得组件的模块中提供服务您可以使用@component注释下的providers属性。它将只注入到您的组件中,并且在加载组件时,它将始终创建服务的新实例
@组件({
/* . . . */
提供者:[学生服务]
})
我使用Angular 9遇到了相同的错误,我通过以下方法解决了这个问题:
我希望这也能对您起作用。您必须提供服务。在您的服务类装饰器中尝试
@Injectable({providedIn:'root'})
。@R.Richards-谢谢,这是您的权利,我们可以在这里如何使用Injector?我不想在组件的提供程序中添加我的服务,我想使用Injector您应该在某个地方提供您的服务,然后再使用Injectorthis.injector.get(…)
如果您在应用程序中的某个位置提供了服务,则可以使用。我不想在模块的提供程序中添加我的服务,我想使用injector