我正在编写angular2应用程序,它有两个组件。两个组件都从一个服务获取数据。我已将此服务包含在我的两个组件中,并且我希望在任何组件中有任何数据更改时,它应该更改其他组件视图,因为它们都从相同服务获取日期,并且这些组件更改服务中的数据。
bootstrap应用程序
//main.ts
platformBrowserDynamic().bootstrapModule(AppModule);
App模块代码:
//app.module.ts
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent, OfferFilter, OfferListing],
bootstrap: [ AppComponent ]
})
export class AppModule { }
app组件
//app.component.ts
@Component({
selector: 'app',
template: `<first-component></first-component>
<second-component></second-component>`,
})
export class AppComponent {
}
第一个组件
@Component({
selector: 'first-component',
template: `
<div class="manage">
...
</div>
`,
providers: [WidgetResourcesList]
})
export class OfferFilter {
constructor(public widgetResourcesList: WidgetResourcesList) {
}
selectFilter($event: any) {
this.widgetResourcesList.serUserSelection(value, checked);
}
}
第二部分
@Component({
selector: 'second-component',
template: `
<table>
....
</table>
`,
providers: [WidgetResourcesList]
})
export class OfferListing {
constructor(public widgetResourcesList: WidgetResourcesList) {
}
}
WidgetResourcesList类,在组件
中提供export class WidgetResourcesList {
//noinspection TypeScriptUnresolvedVariable
private widgetResources = window.widgetResources;
private userSelection: Array<any> = [];
private header: Array<any>;
private offerList: Array<any>;
setOffer(header: Array<any>, offerList: Array<any>) {
this.header = header==null? [] : header;
this.offerList = offerList==null? [] : offerList;
}
getOffer() {
return {'header': this.header, 'offerList': this.offerList};
}
private filterList : Array<any> = [
{
'id': 'VIDEO',
'name': 'Television',
'desc': 'Cable TV and On Demand',
'checked': false
},
{
'id': 'XHS',
'name': 'Home',
'desc': 'Security, control and more',
'checked': false
},
];
getFilterList() {
return this.filterList;
}
serUserSelection(id: String, checked: boolean) {
if(checked) {
this.userSelection.push(id);
} else {
if(this.userSelection.indexOf(id) >=0){
this.userSelection.splice(this.userSelection.indexOf(id),1);
}
}
}
getOffersForPhone() {
let userSelectionStr = this.userSelection.sort().join('$');
if(userSelectionStr==="") {
userSelectionStr = "VIDEO"
}
return this.getOffer();
}
}
我做错了什么?
答案 0 :(得分:2)
您需要将WidgetResourcesList
添加到模块中的提供程序。
您需要将其从组件中的提供程序中删除。
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent, OfferFilter, OfferListing],
bootstrap: [ AppComponent ],
providers: [ WidgetResourcesList ]
})
export class AppModule { }
每次在实例化组件时向组件的提供者添加服务时,所有提供者也都会被实例化,因此您将获得不同的服务实例。