我正在构建一个Angular 4应用程序,我有2个单独的页面,一个Detail页面和一个Edit页面,每个页面都有自己的组件。
当用户在“编辑”页面上编辑模型时,我会将它们重定向回“详细信息”页面,如下所示:
// This is within my RetailerEditComponent
save(): void {
this.retailerService.updateRetailer(this.retailer)
.then(() => this.router.navigate(['/admin/retailer']));
}
在admin / retailer页面中,我有一个RetailerDetailComponent,如下所示:
export class RetailerDetailComponent {
retailer: Retailer;
public hasBeenUpdated: boolean = false;
constructor(
private retailerService: RetailerService,
) {
console.log("in RetailerDetailComponent");
}
}
如何从其他页面将bool hasBeenUpdated设置为true?
更新
我喜欢EventEmitter的想法,但遇到了问题。
我的零售商服务:
export class RetailerService {
public OnRetailerUpdated = new EventEmitter();;
updateRetailer(retailer: Retailer): Promise<Retailer> {
this.OnRetailerUpdated.next(true);
return new Promise((resolve, reject) => {
apigClient.retailerVPut({}, retailer, {})
.then(function (result) {
resolve(result.data[0])
}).catch(function (result) {
reject(result)
});
}
})
});
}
}
在我的RetailerDetailComponent中:
export class RetailerDetailComponent实现LoggedInCallback { 零售商:零售商;
public showError: boolean;
constructor(
private retailerService: RetailerService) {
}
ngOnInit(): void {
this.retailerService
.OnRetailerUpdated
.subscribe(value => {
this.showError = true;
console.log('Event thingy worked')
});
}
但是控制台消息没有显示
答案 0 :(得分:2)
你有几个选择:
第一个是在服务中创建一个零售商地图,指出哪些零售商已更新,并在您调用updateRetailer
方法时设置价值。
public retailersUpdateStates: { [id: string]: Retailer } = {};
以及检查状态的方法:
public hasBeenUpdated(retailer: Retailer) {
return !!this.retailersUpdateStates[retailer.id]
}
调用方法时:
retailersUpdateStates[retailer.id] = true;
在你的组件中:
public get hasBeenUpdated() {
return this.retailersService.hasBeenUpdated(this.retailer);
}
第二个是将hasBeendUpdated
属性添加到Retailer
模型并相应地更新它。在组件模板中,您可以这样做:
{{ retailer?.hasBeenUpdated }}
第三个是使用路由器参数,这是已经更新的零售商ID。 (但这似乎并不那么花哨)。
还有更多方法,例如使用ngrx进行状态管理。有了这个&#34;单一的真理来源&#34;如@ faisal的回答所述,分享各个组成部分或使用受管理零售商状态的rxjs将是一件轻而易举的事。
答案 1 :(得分:1)
使用例如RetailerService用于共享组件之间的公共变量。
答案 2 :(得分:1)
最好的方法是使用EventEmitter订阅。示例如下:
public OnRetailerUpdated = new EventEmitter&lt; boolean&gt;();
this.OnRetailerUpdated.next(真);
this.retailerService .OnRetailerUpdated .subscribe(value =&gt; { //在此执行相应的操作});
private subscription;
ngOnInit() {
this.subscription = this.retailerService.OnRetailerUpdated
.subscribe(value => {
// Perform the appropriate action here
});
};
ngOnDestroy() {
this.subscription.unsubscribe();
};