【发布时间】:2017-10-21 03:53:21
【问题描述】:
我在显示通过 Angular 中的 Http get 请求接收到的对象属性时遇到问题。我试图在 ngOnInit() 方法中调用 HTTP 请求,这似乎工作正常:我收到了我需要的对象。但是后来我无法在 http 文件中显示它(属性未定义)。似乎我无法将可观察对象连接到对象属性。我做错了什么?
组件:
import { Component, OnInit } from '@angular/core';
import {Package} from "../shared/package";
import { Http} from "@angular/http";
import 'rxjs/Rx';
@Component({
selector: 'app-basket',
templateUrl: './basket.component.html',
styleUrls: ['./basket.component.css']
})
export class BasketComponent implements OnInit {
package: Package;
private baseUrl: string = 'https://basket-211b4.firebaseio.com/.json';
constructor(private http: Http) { }
ngOnInit() {
this.http.get(`${this.baseUrl}`).subscribe(
(result) =>{
this.package = result.json();
console.log(this.package);
}
)
}
Http 文件:
<li class="row totals">
<span class="price" >{{ package.id }}</span>
</li>
包类:
import {User} from "./user";
import {Service} from "./service";
export class Package {
constructor(public id: number, public totalCost: number, public dateCreated: string, public user: User,
public services: Service[]){}
}
控制台错误:./BasketComponent 类 BasketComponent 中的错误 - 内联模板:31:29 原因:无法读取未定义的属性 'id'
控制台中显示的对象:Object {dateCreated: "2017-05-14T18:47:56.000+0000", id: 1, services: Array(3), totalCost: 3600, user: Object}
【问题讨论】:
-
Http 发送 AJAX 请求。 AJAX 中的第一个 A 表示 异步。因此,当组件首次显示时,还没有填充 package 字段。它只是稍后填充,当 HTTP 响应返回并且传递给 subscribe 的回调函数正在执行时。使用
package?.id。或者使用 *ngIf 仅显示可用的包。
标签: angular angular2-http