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({}));
  • 相关阅读:
    centos 研究
    python学习6 web开发
    python学习5 常用三方模块
    python学习4 常用内置模块
    python学习 3笔记
    SQLite
    mysql
    python学习 2数学公式
    python学习 1基础
    shell example02
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9551849.html
Copyright © 2011-2022 走看看