我有一个 Angular 4 组件,它从服务中检索数据,然后更新视图。当我的服务检索数据并更新组件的属性时,该属性不会在 UI 中更新。我曾尝试使用 NgZone 和 ChangeDetectionRef 强制更新,但均未成功。我的看法是:
<h1> {{ extractedData == false ? 'Enter' : 'Confirm'}} ACH Data</h1>
<form>
<div class="form-group">
<label>Account #</label>
<input type="text" name="accountNum" [(ngModel)]="processedImage.achResponse.accountNumber" class="form-control"/>
</div>
<div class="form-group" *ngIf="!extractedData">
<label>Confirm Account #</label>
<input type="text" name="confirmAccountNum" [(ngModel)]="confirmAccountNumber" class="form-control" />
</div>
<div class="form-group">
<label>Routing #</label>
<input type="text" name="routingNum" [(ngModel)]="processedImage.achResponse.routingNumber" class="form-control" />
</div>
<button type="button" class="btn btn-lg btn-primary" style="border-radius: 0; margin: 1em; width: 90%">Submit</button>
</form>
我的组件是:
import { Component, OnInit, NgZone, ChangeDetectorRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Logger } from 'angular2-logger/core';
import { ProcessedImage } from '../../core/models/ProcessedImage';
import { ProcessedImageService } from '../../core/services/processedImage.service';
@Component({
templateUrl: './payment-data.component.html',
styleUrls: ['./payment-data.component.css']
})
export class PaymentDataComponent {
public extractedData: boolean;
public processedImage : ProcessedImage;
public confirmAccountNumber: string;
public headerText: string;
constructor(private _route: ActivatedRoute,
private _imgSvc: ProcessedImageService,
private _log: Logger,
private _cdRef: ChangeDetectorRef,
private _zone: NgZone)
{
this.extractedData = false;
this._log.info("initializing PaymentData component");
this.processedImage = new ProcessedImage();
this.confirmAccountNumber = "";
this._route.paramMap.subscribe((m) => {
let trx = m.get("transactionId");
if (trx != null) {
let img = this._imgSvc.get(trx);
this._log.info("Image Received from svc", img);
if (img != null) {
this._log.info("Image is not null, updating stuff.");
this.extractedData = true;
this.processedImage = img;
}
}
});
}
public getHeader() {
return this.extractedData ? "Confirm" : "Enter";
}
}
这就是输出的样子。
显然有些东西坏了,因为 H1 静态内容没有出现。预期的结果是字段中应该有字符串值,并且标题应该是Confirm ACH Data
. 这就是我刷新时页面的样子(_imgSvc 将无法找到事务,因此“提取”将是错误的)。这让我相信它与路由有关,但是日志条目都表明构造函数被正确调用并在路由器将您带到此页面时返回正确的数据。这也是一条子路线,如果这有所作为的话。