Angular 2 - 使用共享服务

Mar*_* Jr 11 angular2-services angular

看起来共享服务是解决许多情况的最佳实践,例如组件之间的通信或替换角度1的旧$ rootscopecope概念.我正在尝试创建我的,但它不起作用.有帮助吗?ty !!!

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){}
}
Run Code Online (Sandbox Code Playgroud)

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;
}
}
Run Code Online (Sandbox Code Playgroud)

Thi*_*ier 9

大多数情况下,您需要在引导应用程序时定义共享服务:

bootstrap(AppComponent, [ SharedService ]);
Run Code Online (Sandbox Code Playgroud)

而不是在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{
  (...)
}
Run Code Online (Sandbox Code Playgroud)

这样,他们将为两个组件共享相同的服务实例.OtherComponent将使用父组件(AppComponent)中的那个.

这是因为Angular2的"分层注入器"功能.有关详细信息,请参阅此问题: