zoukankan      html  css  js  c++  java
  • [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({}));
  • 相关阅读:
    SpringMVC概述
    Spring 声明式事务
    Spring_AOP切面编程
    Spring DI依赖注入
    Spring IOC控制反转
    Spring解耦和耦合
    Spring概述
    HTTP协议常见状态码
    TCP/IP协议的认识
    设计模式-工厂模式(factory)
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9551849.html
Copyright © 2011-2022 走看看