看起来共享服务是解决许多情况的最佳实践,例如组件之间的通信或替换角度1的旧$ rootscope概念。我正在尝试创建我的我的产品,但它没有用。有什么帮助吗?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){}
}
其他组件
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具有“分层注入器”功能。有关更多详细信息,请参见以下问题:
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句