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({}));
  • 相关阅读:
    make menuconfig出现乱码
    内存中的变量和值
    is&==
    python小整数池
    生成器
    GIL
    grub rescue问题修复
    期末考试
    期末要求
    选课练习
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9551849.html
Copyright © 2011-2022 走看看