Angular 2 - 使用共享服务

Angular 2 - Using Shared Service

看起来共享服务是解决许多情况的最佳实践,例如组件之间的通信或替代旧的 $rootscope 概念 angular 1. 我正在尝试创建我的,但它不是在职的。有什么帮助吗?泰!!!

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

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 属性中再次定义它。这样您就可以为整个应用程序提供一个服务实例。


在您的情况下,由于 OtherComponentAppComponent 的子组件,只需像这样删除 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 的 "hierarchical injectors" 特性。详情请看这个问题:

  • What's the best way to inject one service into another in angular 2 (Beta)?

您需要在您的模块中添加一个全局提供程序,然后您不需要在每个组件中添加此提供程序。试试这个

app.module.ts

@NgModule({
    imports: [BrowserModule, FormsModule, HttpModule],
    declarations: [AppComponent, LoginComponent, InComponent],
    providers: [LoginService],
    bootstrap: [AppComponent]
})

app.component.ts

@Component({
    moduleId: module.id,
    selector: 'app',
    templateUrl: './app.component.html'
})
export class AppComponent {
    constructor(public loginService: LoginService) {

    }
}

login.component.ts

@Component({
    moduleId: module.id,
    selector: 'login',
    templateUrl: './login.component.html'
})
export class LoginComponent {

    constructor(public loginService: LoginService) {

    }
}

我希望这对你有用。

除了你的需求及其解决方案,你还可以考虑使用Facade + Shared Services。我这里有一个小项目:https://github.com/cmandamiento/angular-architecture-base