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({}));
  • 相关阅读:
    django–url
    SQLServer-镜像配置
    linux-阿里云ECS部署PPTP(centos)
    linux- svn服务器
    python(7)– 类的反射
    python(7)–类的多态实现
    python(6)-shutil模块
    python(6)-执行shell命令
    python(6)-类
    nagios–配置文件
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9551849.html
Copyright © 2011-2022 走看看