问题描述
我正在尝试为我的应用程序提供共享服务.
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) {}
我遇到了一个错误:Can't resolve all parameters for 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中的共享服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!