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