Angular很新穎。我檢查了類似的問題,但他們要麼深入細節,要麼只是不理解解決方案。Angular 2 - 無法讀取未定義的屬性'...'
實際的錯誤: 「無法讀取屬性 'idPlanet' 的未定義在Object.eval [如updateRenderer(PlanetComponent.html:11)」
問題: planetDetail.idPlanet是未定義最可能?
可疑: getPlanetDetail()
planet.component.html:
<div class="col-sm-9">
ID: {{ planetDetail.idPlanet }}
</div>
planet.component.ts:
import {
Component,
OnInit
} from '@angular/core';
import { Planet } from './planet';
import { PlanetService } from './planet.service';
@Component({
selector: 'planets',
templateUrl: './planet.component.html'
})
export class PlanetComponent implements OnInit {
private planets: Planet[];
private planetDetail: Planet;
constructor(
private planetService: PlanetService
) {}
public ngOnInit(): void {
this.getPlanetDetail();
this.getPlanets();
}
public getPlanets() {
this.planetService.getPlanets()
.subscribe(
(planets) => this.planets = planets
);
}
public getPlanetDetail() {
this.planetService.getPlanetDetail()
.subscribe(
(planets) => this.planetDetail = planets
);
}
}
planet.service.ts:
import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Planet } from './planet';
@Injectable()
export class PlanetService {
private planetsUrl = 'http://localhost/index.php/api/planet/'; // URL to web api
// Injecting the http client into the service
constructor(private http: Http) {}
public getPlanets(): Observable<Planet[]> {
return this.http.get(this.planetsUrl + 'planets/id_sol/1')
.map(this.parseData)
.catch(this.handleError);
}
public getPlanetDetail(): Observable<Planet> {
return this.http.get(this.planetsUrl + 'planet/id_planet/1')
.map(this.parseData)
.catch(this.handleError);
}
private parseData(res: Response) {
let body = res.json();
if (body instanceof Array) {
return body || [];
} else {
return body.post || {};
}
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
我不知所措tbh,我試圖從getPlanets()生成我的getPlanetDetail()方法,它工作正常。我應該使用承諾嗎?
我很難搞清楚我可以把console.log()調試到什麼地方。我正在使用Github的角度初學者套件。
謝謝你的時間。
編輯1:API輸出{「idPlanet」:「1」,「名稱」:「地球」}
如果你確定'planetDetail'是在某個點(異步)填充,嘗試'ID:{{planetDetail?.idPlane t}} – Phix
檢查這一個:'(planets)=> this.planetDetail = planets'。很可能'行星'是不確定的。因此,在'parseData'方法內部進行控制以查看您的http調用的響應情況。 –
是的,我不知道還有什麼不對應的東西。 – qwertzman