[Angular] 'providedIn' for service
There is now a new, recommended, way to register a provider, directly inside the @Injectable()
decorator, using the new providedIn
attribute.
@Injectable({ providedIn: 'root' }) export class UserService { }
When you use 'root'
, your injectable will be registered as a singleton in the application, and you don’t need to add it to the providers of the root module. Similarly, if you use providedIn: UsersModule
, the injectable is registered as a provider of the UsersModule
without adding it to the providers of the module.
In the same spirit, you can now declare an InjectionToken
and directly register it with providedIn
and give it a factory
:
export const baseUrl = new InjectionToken<string>('baseUrl', { providedIn: 'root', factory: () => 'http://localhost:8080/' });
Note that it also simplifies unit testing. We used to register the service in the providers of the testing module to be able to test it.
Before:
beforeEach(() => TestBed.configureTestingModule({
providers: [UserService]
}));
Now, if the UserService
uses providedIn: 'root'
:
After:
beforeEach(() => TestBed.configureTestingModule({}));
相关文章
- [Unit Testing Angular] RxJS Marble testing for Component
- [Angular] How to show global loading spinner for application between page navigation
- [Angular] Using Pipe for function memoization
- [Angular] Show a Loading Indicator for Lazy Routes in Angular
- [Angular CLI] Build application without remove dist folder for Docker Volume
- [Angular] Short Imports with TypeScript Path Mapping
- [Angular] Providers and useFactory
- [Angular] NgRx/effect, why to use it?
- [AngularJS] angular-md-table for Angular material design
- [Angular 2]ng-class and Encapsulated Component Style2
- [Angular 2] Create a simple search Pipe
- [Whole Web] [AngularJS] Localize your AngularJS Application with angular-localization
- [AngularJS] Angular 1.3 $submitted for Form in Angular
- [Angular] Standalone component - routes top level provide share for all child routes
- [AngularJS] angular-md-table for Angular material design
- [AngularJS] Using the LocalForage library for offline storage with Angular
- SAP Spartacus angular.json 中定义的 serve-ssr
- Angular 依赖注入的一个常见错误 NullInjectorError, No provider for XXX
- Angular 依赖注入框架里 useExisting 和 useClass 的使用场景
- Angular InjectionToken APP_INITIALIZER multi 标志位不同值的情况讨论
- Angular:why click add button does not work for the second time
- 关于 Angular 应用的入口
- Angular 应用里的 vendor.js 是用来干什么的?
- Angular 事件绑定语法在 SAP Spartacus Popover Component 中的一个应用
- Angular应用的angular.json文件字段一览
- Angular structural指令host element的定位调试
- 2020国庆节 Angular structual 指令学习笔记(<ng-template>) 包含语法糖解糖过程