我在显示一个对象的属性时遇到麻烦,通过Angular中的Http get请求收到。我试图在ngOnInit()方法中调用HTTP请求,这似乎工作正常:我收到了我需要的对象。但后来我在http文件中显示它有麻烦(属性是unifined)。似乎我无法将observable连接到object属性。我做错了什么?
组件:
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>
Package类:
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}
答案 0 :(得分:0)
您可以使用安全导航(?)运算符来显示属性
<li class="row totals">
<span class="price" >{{ package?.id }}</span>
</li>