简体   繁体   English

Angular2中的共享服务

[英]Shared service in Angular2

I'm trying to make a shared service for my app. 我正在尝试为我的应用程序提供共享服务。

import { Injectable } from '@angular/core';

@Injectable()
export class SharedService {
  testService() {
    console.log('share!');
  }
}

Then I inject it in my app.component's providers but when I tried to call it in the constructor of a child component like this: constructor(public sharedService: SharedService) {} I've got an error: Can't resolve all parameters for MyComponent . 然后,将其注入到app.component的提供程序中,但是当我尝试在子组件的构造函数中调用它时,如下所示: constructor(public sharedService: SharedService) {}我遇到了一个错误: Can't resolve all parameters for MyComponent I also tried to inject it in my app.module providers and also got this error. 我还尝试将其注入到我的app.module提供程序中,并且也收到此错误。 What should I do? 我该怎么办? How to inject it properly? 如何正确注射? Can anyone provide an example of proper shared service for antire app(it has several modules)? 谁能为antire应用程序提供适当的共享服务的示例(它具有多个模块)?

I have routing sistem and I want to have a shared service and change it's data from the component which module is currently represented. 我有路由系统,我想拥有一个共享服务,并从当前代表哪个模块的组件中更改其数据。

I believe you use latest version and want to use singleton service. 我相信您使用的是最新版本,并希望使用单例服务。 For that you have to register your service in @NgModule({}) as shown here, 为此,您必须在@NgModule({})注册服务,如下所示,

import {Sharedservice} from 'valid path';

@NgModule({
   imports:[BroswerModule],
   ...
   providers:[SharedService]
})

Now, In child and parent component just import Sharedservice at the top of the file. 现在,在子组件和父组件中,只需在文件顶部导入Sharedservice即可。

NOTE : Remove providers:[SharedService] from each component. 注意:从每个组件中删除providers:[SharedService]

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

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