组件提供者和模块提供者的区别 [英] Components providers and Module providers difference

查看:160
本文介绍了组件提供者和模块提供者的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@Components providers属性和@Module providers之间的区别是什么?

Which's the difference between @Components providers property and @Module providers?

两者代表什么?

编辑

我有两个组成部分:LoginComponentSigninComponent.另一方面,我正在使用定制库中的UserService.此UserService服务正在寻找一个opaquetoken BASE_PATH:

I've two components: LoginComponent and SigninComponent. By other hand I'm using an UserService from a custom made library. This UserService service is looking for an opaquetoken BASE_PATH:

@Injectable()
export class UsersService {
    constructor(@Optional()@Inject(BASE_PATH)

BASE_PATH是:

export const BASE_PATH = new OpaqueToken('basePath');

此opaqueToken是在AppModule上设置的:

This opaqueToken is set on AppModule:

@NgModule({
  bootstrap: [ App ],
  declarations: [
    App,
    ErrorComponent
  ],
  providers: [
    ENV_PROVIDERS,

其中ENV_PROVIDERS是根据environtment.ts上的环境设置设置的:

where ENV_PROVIDERS is set according environtment settings on environtment.ts:

if ('production' === ENV) {
  enableProdMode();

  PROVIDERS = [
    ...PROVIDERS,
    // custom providers in production
    { provide: BASE_PATH, useValue: 'http://public.sample.com:8082/commty/cmng' }
  ];

} else {

  // Development
  PROVIDERS = [
    ...PROVIDERS,
    // custom providers in development
    { provide: BASE_PATH, useValue: 'http://localhost:8082/commty/cmng' }
  ];

}

export const ENV_PROVIDERS = [
  ...PROVIDERS
];

我正在设置所有内容:

@NgModule({
  declarations: [
    SigninComponent
  ],
  providers: [ UsersService ]
})
export default class SigninModule {

@NgModule({
  declarations: [
    LoginComponent
  ],
  providers: [ UsersService ]
})
export default class LoginModule {

因此,在组件上,我不将任何服务作为提供程序导入,我只声明它们.

So, on components, I don't import any Service as providers, I only declare them.

尽管如此,当我加载SigninModule时,我所有的网络请求都发送到了localhost.但是,当我加载LoginModule时,请求将发送到localhost:8282

Nevertheless, when I load SigninModule all my network request are sent to localhost. However, when I load LoginModule requests are sent to localhost:8282

推荐答案

如果在组件内部提供服务,则该服务将是本地的. 因此,如果您有两个组件实例,那么您将有两个服务实例.

If you provide your service inside your component, it will be local to it. So if you have two instance of your component, you will have two instance of your service.

现在,如果您在模块内部提供服务,则该服务将是全局的,并且如果您有组件的两个实例,则它们将共享该服务的同一实例.

Now if you provide your service inside your module, it will be global and if you have two instance of your component, they will share the same instance of the service.

如果您不了解,请告诉我,我将为您提供有关plunker的示例.

Tell me if you don't understand, I will provide you an example on plunker.

这篇关于组件提供者和模块提供者的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆