Angular2 不会触发ChangeDetection
单击事件后的事件。下面的代码片段用于将数据从一个组件获取到另一个组件。
点击事件
(click)="$event.preventDefault(); setApartmentObject(FlatObject)";
ApartmentOverview组件
constructor(private _apart:ApartmentService) {}
setApartmentObject(flat:ApartmentObject) {
this._apart.setApartmentDetails(flat);
}
公寓服务
Injectable()
export class ApartmentService {
apartmentDetails:ApartmentObject
getApartmentDetails():Observable<ApartmentObject> {
return Observable.create((observer) => {
observer.next(this.apartmentDetails);
observer.complete();
});
}
setApartmentDetails(value:ApartmentObject) {
this.apartmentDetails = value;
}
}
公寓细节组件
constructor(private _apart:ApartmentService)
get apartmentDetails() {
this._apart.getApartmentDetails().subscribe(data => {
this._apartmentDetails = data;
});
return this._apartmentDetails;
}
在 HTML 文件中
<p><strong>{{apartmentDetails.name || 'Musterwohnung'}}</strong></p>
我也尝试用事件发射器解决这个问题,但没有成功。只有以下脏修复有效:
constructor(private _ref:ChangeDetectorRef) {
this._ref.detach();
setInterval(() => {
this._ref.detectChanges();
}, 300);
}