看起来共享服务是解决许多情况的最佳实践,例如组件之间的通信或替换旧的 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){}
}
其他组件.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 的“分层注入器”特性。有关更多详细信息,请参阅此问题:
- 在 Angular 2(Beta)中将一项服务注入另一项服务的最佳方法是什么? https://stackoverflow.com/questions/34804298/whats-the-best-way-to-inject-one-service-into-another-in-angular-2-beta/34807397
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)