[英]angular2, assign value to component within router.events does not trigger view update?
When navigating to other routes, I will save some values in service. 导航到其他路线时,我将在服务中保存一些值。
Navigate back, I grab the values from the service and assign to component variable again. 向后浏览,我从服务中获取值,然后再次分配给组件变量。
the component variable is bind to input
[(ngModel)]
. 组件变量绑定到input
[(ngModel)]
。
ngOnInit() {
this.dataSource = new PropertyDataSource(this.paginator, this.propertyService);
this.displayedColumns = this.tableHeaders.map((header) => header.key);
this.selectedOption = this.propertyOptions[0];
this.paginatorService.i18n(this.paginator, 'cn');
this.router.events.filter((event) => event instanceof NavigationEnd).pairwise()
.subscribe((events: any) => {
const prevRouteUrl: string = events[0].url;
const currentRouteUrl: string = events[1].url;
if (prevRouteUrl.indexOf(`${currentRouteUrl}/edit`) !== -1) {
const lastQueryCondition: IQueryCondition = this.propertyService.getQueryCondition();
const { pageIndex, keyword } = lastQueryCondition;
//TODO: why view not update???
this.zone.run(() => {
this.keyword = keyword;
this.paginator.pageIndex = pageIndex;
});
this.getPropertiesByName(keyword, pageIndex + 1);
}
});
}
HTML: HTML:
<input type="text" name="keyword" placeholder="keyword" [(ngModel)]='keyword' required />
The problem is when I assign the value to the component variable, eg this.keyword
, the view does not update which means the input
is empty. 问题是当我将值分配给组件变量(例如this.keyword
,视图不会更新,这意味着input
为空。
Even I use NgZone
and ChangeDetectorRef
, the view still not update. 即使我用NgZone
和ChangeDetectorRef
,观点依然没有更新。
What if instead of subscribing to router events you added a getter to your component: 如果不是订阅路由器事件,而是在组件中添加了getter,该怎么办:
get keyword(): string {
return this.propertyService.getQueryCondition().pageIndex;
}
I have a blog post illustrating this technique here: https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/ 我在这里有一篇博客文章说明了这种技术: https : //blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/
And a plunker here: https://plnkr.co/edit/KT4JLmpcwGBM2xdZQeI9?p=preview 还有一个小家伙: https ://plnkr.co/edit/KT4JLmpcwGBM2xdZQeI9 ? p = preview
My service basically looks like this: 我的服务基本上如下所示:
import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
serviceData: string;
}
and the component like this: 和这样的组件:
import {Component} from '@angular/core'
import { DataService } from './data.service';
@Component({
template: `
<div>
<h2>Data from A: {{ data }} </h2>
<input [(ngModel)] = data />
<br><br>
<a [routerLink]="['/b']">Go to B</a>
</div>
`,
})
export class A {
get data():string {
return this.dataService.serviceData;
}
set data(value: string) {
this.dataService.serviceData = value;
}
constructor(public dataService: DataService) { }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.