如何在Angular中指定服务中的提供者?
提供者告诉注入器如何创建服务。在注入器创建服务(或提供任何其他类型的依赖关系)之前,必须使用提供程序配置注入器 此代码也来自该链接:如何在Angular中指定服务中的提供者?,angular,typescript,dependency-injection,Angular,Typescript,Dependency Injection,提供者告诉注入器如何创建服务。在注入器创建服务(或提供任何其他类型的依赖关系)之前,必须使用提供程序配置注入器 此代码也来自该链接: import { Injectable } from '@angular/core'; import { HEROES } from './mock-heroes'; @Injectable({ // we declare that this service should be created // by the root application inj
import { Injectable } from '@angular/core';
import { HEROES } from './mock-heroes';
@Injectable({
// we declare that this service should be created
// by the root application injector.
providedIn: 'root',
})
export class HeroService {
getHeroes() { return HEROES; }
}
这里的“根”是注入器。谁是提供者
@Injectable()decorator具有providedIn元数据选项,在该选项中,您可以使用根注入器或特定模块的注入器指定修饰服务类的提供者
在我的代码中,我直接导入了一个服务,如下所示,并将其注入构造函数中:
import { BlogContentsService } from '../blog-contents.service'
...
constructor( private objBlogContentsService: BlogContentsService)
{
}
这是正常工作。我还没有指定任何提供商
如何在此处指定提供程序?为什么它在我的类中没有指定提供者的情况下工作
在myapp.module.ts
中
@NgModule({
declarations:
[
AppComponent,
TitleBodyFormComponent,
DashboardComponent,
MyElseDirective,
ElseDirective,
WhitespaceValidatorDirective
],
imports:
[
BrowserModule,
AppRoutingModule,
// ------ Added by me for reactive forms:
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
提供程序:[]
列表为空。当您在其中提供“根”时,此服务将自动注入根注入器。并可在整个应用程序中使用。但是,如果您从装饰器中删除“providedIn”:“root”。您需要将其导入所需的提供者数组中
这在“root”中提供,在angular中引入了树可访问提供程序的概念
更多详细信息请访问:-那么提供者的概念已经过时了吗?不,在各种概念中,您仍然需要提供者。取决于用例。请在回答中提到那些用例。这与这个问题无关