简体   繁体   English

Root与@Injectable提供的元数据有什么选择

[英]What is the choice forRoot vs @Injectable providedIn metadata

I can use ModuleWithProviders forRoot static methods to register some services with roots modules since those services shared among few components within different modules. 我可以使用ModuleWithProviders forRoot静态方法向根模块注册某些服务,因为这些服务在不同模块内的几个组件之间共享。

export class SharedModule {
    static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [ CounterService ]
    }
  }
}

But with angular 6 if a services is need to register with root injector simply can be done with @Injector decorator with providedIn metadata set as 'root'. 但是对于角度6,如果需要向根注入器注册服务,只需使用@Injector装饰器(将provedIn元数据设置为“根”)即可完成。

@Injectable({
  providedIn: 'root'
})
export class UserService {

}

So what approach should be appropriate means what would be way i should follow? 那么哪种方法应该合适,那意味着我应该遵循什么方法?

also does forRoot going to be obsolete?? forRoot也将过时吗?

What happen to Provider Array in Modules?? 模块中的提供程序数组会发生什么?

In angular when a module provides both declaration and providers it would duplicate the provider instances when injecting in child that would cause issues on instances which are probably meant to be singletons. 在角度上,当模块同时提供声明和提供程序时,它将在注入子级时复制提供程序实例,这可能会导致实例上可能是单例的问题。 For this reason Angular provides a way to separate providers out of the module so that same module can be imported into the root module with providers and child modules without providers. 因此,Angular提供了一种将提供者从模块中分离出来的方法,以便可以将具有提供者的相同模块导入到具有提供者的根模块中,而将没有提供者的子模块导入到根模块中。

providedIn is the new syntax to create singletons (ie providers declared in the root injector). providedIn是创建单例(即在根注入程序中声明的providedIn )的新语法。

You can provide it in any other module, but root is the shorthand for AppModule . 您可以在任何其他模块中提供它,但rootAppModule的简写。

It allows you to install dependencies pretty fast and without the need of any additional configuration. 它使您可以非常快速地安装依赖项,而无需任何其他配置。

Hence, forRoot won't be obsolete, because it allows one to be able to configure a module through it. 因此, forRoot不会过时,因为它允许人们通过它配置模块。

I'd say you should use the providedIn syntax for your providers, and if they need configuration, you can use forRoot . 我想说您应该为providedIn程序使用providerIn语法,如果他们需要配置,则可以使用forRoot

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM