angular2,为router.events中的组件赋值,不会触发视图更新?

时间:2017-08-10 06:05:50

标签: angular

  1. 导航到其他路线时,我会保存一些服务价值。

  2. 向后导航,我从服务中获取值并再次分配给组件变量。

  3. 组件变量绑定到input [(ngModel)]

  4. 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:

    <input type="text" name="keyword" placeholder="keyword" [(ngModel)]='keyword' required />
    

    问题是当我将值分配给组件变量时,例如this.keyword,视图不会更新,这意味着input为空。

    即使我使用NgZoneChangeDetectorRef,视图仍然无法更新。

1 个答案:

答案 0 :(得分:0)

如果不是订阅路由器事件而是为组件添加了一个getter,那该怎么办:

  get keyword(): string {
     return this.propertyService.getQueryCondition().pageIndex;
  }

我在这里有一篇博文说明这种技巧:https://blogs.msmvps.com/deborahk/build-a-simple-angular-service-to-share-data/

这里有一个吸烟者:https://plnkr.co/edit/KT4JLmpcwGBM2xdZQeI9?p=preview

我的服务基本上是这样的:

import { Injectable } from '@angular/core';

@Injectable() 
export class DataService {
  serviceData: string; 
}

和这样的组件:

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) { } 
}