看起来共享服务是解决许多情况的最佳实践,例如组件之间的通信或作为 angular 1 的旧 $rootscope 概念的替换。我正在尝试创建我的,但它不起作用。有什么帮助吗?泰!!!
应用程序组件.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){}
}
其他.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;
}
}
最佳答案
大多数时候,您需要在引导应用程序时定义共享服务:
bootstrap(AppComponent, [ SharedService ]);
并且不再在组件的 providers
属性中定义它。这样您将拥有用于整个应用程序的单个服务实例。
在你的例子中,由于 OtherComponent
是你的 AppComponent
的子组件,只需删除 providers
属性,如下所示:
@Component({
selector : "other",
// providers : [SharedService], <----
template : `
I'm the other component. The shared data is: {{data}}
`,
})
export class OtherComponent implements OnInit{
(...)
}
这样,他们将为两个组件共享同一个服务实例。 OtherComponent
将使用来自父组件 (AppComponent
) 的组件。
这是因为 Angular2 的“分层注入(inject)器”特性。有关详细信息,请参阅此问题:
关于Angular 2 - 使用共享服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36251368/