Angular2 中的共享服务 [英] Shared service in Angular2

查看:23
本文介绍了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!');
  }
}

然后我将它注入到我的 app.component 的提供者中,但是当我尝试在子组件的构造函数中调用它时,如下所示:constructor(public sharedService: SharedService) {}一个错误:无法解析 MyComponent 的所有参数.我还尝试将它注入我的 app.module 提供程序中,但也出现了此错误.我该怎么办?如何正确注射?任何人都可以为 antire 应用程序提供一个适当的共享服务的例子(它有几个模块)?

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. I also tried to inject it in my app.module providers and also got this error. 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)?

我有路由系统,我想要一个共享服务并从当前代表哪个模块的组件更改它的数据.

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.

推荐答案

我相信您使用的是最新版本并希望使用单例服务.为此,您必须在 @NgModule({}) 中注册您的服务,如下所示,

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,

import {Sharedservice} from 'valid path';

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

现在,在子组件和父组件中,只需在文件顶部导入 Sharedservice.

Now, In child and parent component just import Sharedservice at the top of the file.

注意:从每个组件中删除 providers:[SharedService].

NOTE : Remove providers:[SharedService] from each component.

这篇关于Angular2 中的共享服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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