Response.json() 使用接口绑定到单个对象 - RxJs/Observable 失败

Response.json() bind to single object using interface - RxJs/Observable fails

这种情况在 RESTful API returns 一个 JSON 数组时工作正常 - 但我调用 returns 的网络方法是单个 JSON 对象 - 因此代码已转换为从 <IRegistration[]> to <IRegistration> 一直映射到堆栈上的单个对象。

失败,Chrome 控制台 returns 出现错误,显示应用程序无法在 HTML

中找到任一映射字段

HTML

{{myobject.productId}}
{{myobject.productName}}

JSON

{
  "productId": 1,
  "productName": "My Field Value"
}

界面

export interface IRegistration {
    productId: number;
    productName: string;
}

可观察的

getRegistration(): Observable<IRegistration> {
    return this._http.get(this._svcURL)
        .map((response: Response) => <IRegistration>response.json())
        .do(data => console.log('ALL: ' + JSON.stringify(data)))
        .catch(this.handleError);
}

客户端组件

myobject: IRegistration;

ngOnInit(): void {
    this._registrationService.getRegistration().subscribe(
        reg => this.myobject= reg,
        error => this.errorMessage = <any>error
    );
}

错误

 EXCEPTION: TypeError: Cannot read property 'productId' of undefined in [
{{myobject.productId}}
{{myobject.productName}}

 in SearchComponent@0:0]

我所做的调试指向 observable 中的 response.json() 未能正确映射到 IRegistration - 我似乎找不到正确的语法?

代码看起来不错,我认为问题是你在使用它之前没有初始化 myobject: IRegistration;

doc for lifecycle hook ngOnInit() 说:

Initialize the directive/component after Angular first displays the data-bound properties and sets the directive/component's input properties.

数据在 HTTP 调用 returns 任何结果之前显示,因此当 Angular 尝试呈现它时 myobject 未定义。

您可以使用 ? 忽略未定义的属性,例如 {{ myobject?.productId }} 或先初始化 属性 myobject: IRegistration = <IRegistration>{};