Angular 2 - 使用共享服务 [英] Angular 2 - Using Shared Service
问题描述
看起来共享服务是解决许多情况的最佳实践,例如组件之间的通信或替代 angular 1 的旧 $rootscope 概念.我正在尝试创建我的,但它不起作用.有什么帮助吗?你好!!!
Looks like shared services is the best practice to solve many situations such as communication among components or as replacement of the old $rootscope concept of angular 1. I'm trying to create mine, but it's not working. Any help ? ty !!!
app.component.ts
app.component.ts
import {Component} from 'angular2/core';
import {OtherComponent} from './other.component';
import {SharedService} from './services/shared.service';
@Component({
selector: 'my-app',
providers: [SharedService],
directives: [OtherComponent],
template: `
<button (click)="setSharedValue()">Add value to Shared Service</button>
<br><br>
<other></other>
`
})
export class AppComponent {
data: string = 'Testing data';
setSharedValue(){
this._sharedService.insertData(this.data);
this.data = '';
console.log('Data sent');
}
constructor(private _sharedService: SharedService){}
}
other.component.ts
other.component.ts
import {Component, OnInit} from "angular2/core";
import {SharedService} from './services/shared.service';
@Component({
selector : "other",
providers : [SharedService],
template : `
I'm the other component. The shared data is: {{data}}
`,
})
export class OtherComponent implements OnInit{
data: string[] = [];
constructor(private _sharedService: SharedService){}
ngOnInit():any {
this.data = this._sharedService.dataArray;
}
}
推荐答案
大多数情况下,您需要在引导应用程序时定义共享服务:
Most of time, you need to define your shared service when bootstrapping your application:
bootstrap(AppComponent, [ SharedService ]);
并且不在组件的 providers
属性中再次定义它.这样,您将拥有整个应用程序的单个服务实例.
and not defining it again within the providers
attribute of your components. This way you will have a single instance of the service for the whole application.
在您的情况下,由于 OtherComponent
是您的 AppComponent
的子组件,只需像这样删除 providers
属性:
In your case, since OtherComponent
is a sub component of your AppComponent
one, simply remove the providers
attribute like this:
@Component({
selector : "other",
// providers : [SharedService], <----
template : `
I'm the other component. The shared data is: {{data}}
`,
})
export class OtherComponent implements OnInit{
(...)
}
通过这种方式,他们将为两个组件共享相同的服务实例.OtherComponent
将使用父组件 (AppComponent
) 中的那个.
This way they will shared the same instance of the service for both components. OtherComponent
will use the one from the parent component (AppComponent
).
这是因为 Angular2 的分层注入器"特性.有关更多详细信息,请参阅此问题:
This is because of the "hierarchical injectors" feature of Angular2. For more details, see this question:
这篇关于Angular 2 - 使用共享服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!