在Angular中,providedIn: root
和forRoot
是两种提供服务的方式。
providedIn: root
方式:
这种方式是Angular 6及以上版本中推荐的方式,它会自动在根模块中提供该服务。只需要在服务的元数据中设置providedIn: root
,不需要在任何模块中进行额外的配置。示例代码如下:
// my.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class MyService {
// Service logic here
}
forRoot
模式:
这种方式适用于那些在应用程序的不同部分使用不同配置的服务。它可以在根模块中使用forRoot
方法提供服务,并在其他模块中使用forChild
方法导入服务。示例代码如下:
// my.module.ts
import { NgModule, ModuleWithProviders } from '@angular/core';
import { MyService } from './my.service';
@NgModule({
// Module declarations
})
export class MyModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: MyModule,
providers: [MyService],
};
}
}
// app.module.ts
import { NgModule } from '@angular/core';
import { MyModule } from './my.module';
@NgModule({
imports: [
MyModule.forRoot(),
// Other module imports
],
// Other module declarations
})
export class AppModule {
}
// other.module.ts
import { NgModule } from '@angular/core';
import { MyModule } from './my.module';
@NgModule({
imports: [
MyModule.forChild(),
// Other module imports
],
// Other module declarations
})
export class OtherModule {
}
这样,MyService
将在根模块中提供,并可以在其他模块中使用forChild
导入。