我試圖從包含項目的json文件中獲取一個項目,但我的代碼無法正常工作。Angular 2:試圖在詳細信息頁面中獲取項目
我收到以下錯誤:TypeError: Cannot read property 'name' of undefined
。這是因爲項目變量未正確填寫。
這是服務中的代碼。我如何從json文件獲得服務:
getProject(id: number): Promise<Project> {
return this.http.get(this.url).toPromise().then(x => {
var project: Project
x.json().data.forEach(element => {
if (element.id == id)
{
project = element;
}
});
return project;
}).catch(this.handleError)
}
compareProject(projectA, projectB): number {
if (projectA.id > projectB.id)
return -1;
else if (projectA.id < projectB.id)
return 1;
else
return 0;
}
如果我調試此代碼,我實際上得到正確的項目。 但它不能在HTML文件中工作。
這是網頁:
import { Component, OnInit } from '@angular/core';
import { RouteSegment} from '@angular/router'
import { ProjectsService } from '../services/projects.service';
import { Project } from '../models/project';
@Component({
templateUrl: 'app/pages/projectdetail.page.html',
providers: [ProjectsService]
})
export class ProjectDetail implements OnInit {
id: any;
project: Project;
constructor(private projectsService: ProjectsService, routeSegment: RouteSegment) {
this.id = routeSegment.getParam('id');
}
getProject() {
this.projectsService.getProject(this.id).then(project => {
this.project = project
});
}
ngOnInit() {
this.getProject();
}
}
和HTML,這是錯誤所在:
<div class="container-fluid">
<div class="page-header headercontainer">
</div>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<h1>Project: {{project.name}}</h1>
</div>
另一種解決方案是使用'safe-navigation-operator',請參閱下面的答案 – Dieterg