今天我开始使用Angular 2并且遇到了一个我无法解决的错误。
我有一个'opdracht'服务,它从模拟文件中加载数据。 opdracht组件在主组件中是4倍。第一个是未定义的,后三个是显示的。
我认为承诺有问题。但我无法弄清楚是什么。代码和控制台错误在这里。
我做错了什么?
谢谢,
马腾
控制台错误
main.bundle.js:41251EXCEPTION: Uncaught (in promise): Error: Error in ./OpdrachtComponent class OpdrachtComponent - inline template:0:3 caused by: Cannot read property 'name' of undefined
opdracht.ts
export interface Opdracht {
id: number;
name: string;
}
opdrachten.mock.ts
import { Opdracht } from "./opdracht";
export const OPDRACHTEN: Opdracht[] = [
{
id: 1,
name: "Apple iDrive"
},
{
id: 2,
name: "Lunchroom Bakker"
},
{
id: 3,
name: "Augmented Albert"
},
{
id: 4,
name: "Pecha Kucha"
}
];
opdrachten.service.ts
import {Injectable} from "@angular/core";
import {Opdracht} from "./opdracht";
import {OPDRACHTEN} from "./opdrachten.mock";
@Injectable()
export class OpdrachtenService {
getOpdracht(id: any): Promise<Opdracht> {
return Promise.resolve(OPDRACHTEN[id]);
}
}
opdracht.component.ts
import {Component, OnInit, Input} from "@angular/core";
import {OpdrachtenService} from "../services/opdrachten/opdrachten.service";
import {Opdracht} from "../services/opdrachten/opdracht";
@Component({
selector: 'app-opdracht',
templateUrl: './opdracht.component.html',
styleUrls: ['./opdracht.component.scss'],
providers: [OpdrachtenService]
})
export class OpdrachtComponent implements OnInit {
@Input() private id: any;
protected opdracht: Opdracht;
constructor(private opdrachtenService: OpdrachtenService) { }
getOpdracht(): void {
this.opdrachtenService.getOpdracht(this.id)
.then((opdracht: Opdracht) => {
this.opdracht = opdracht
})
;
}
ngOnInit() {
this.getOpdracht();
}
}
opdracht.component.html
<p>{{ opdracht.name }}</p>
home.component.html
<app-header></app-header>
<app-foto></app-foto>
<app-ik></app-ik>
<app-opdracht [id]="0"></app-opdracht>
<app-opdracht [id]="1"></app-opdracht>
<app-opdracht [id]="2"></app-opdracht>
<app-opdracht [id]="3"></app-opdracht>
<app-footer></app-footer>
答案 0 :(得分:2)
当Angular评估绑定但尚未到达异步值时,使用安全导航操作符来避免错误:
<p>{{ opdracht?.name }}</p>