m44rt3np44uw m44rt3np44uw - 11 months ago 71
Javascript Question

Angular service promise first is undefined

Today I started with Angular 2 and already came across an error I can't solve.

I have an 'opdracht' service which is loading data out of a mock file. The opdracht component is 4 times in the home component. The first is undefined and the last 3 are showing.

I think there is something wrong with the promise. But I can't figure out what. The code and the console error is down here.

What am I doing wrong?



Console error

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


export interface Opdracht {
id: number;
name: string;


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"


import {Injectable} from "@angular/core";
import {Opdracht} from "./opdracht";
import {OPDRACHTEN} from "./opdrachten.mock";

export class OpdrachtenService {

getOpdracht(id: any): Promise<Opdracht> {
return Promise.resolve(OPDRACHTEN[id]);


import {Component, OnInit, Input} from "@angular/core";
import {OpdrachtenService} from "../services/opdrachten/opdrachten.service";
import {Opdracht} from "../services/opdrachten/opdracht";

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 {
.then((opdracht: Opdracht) => {
this.opdracht = opdracht

ngOnInit() {


<p>{{ opdracht.name }}</p>


<app-opdracht [id]="0"></app-opdracht>
<app-opdracht [id]="1"></app-opdracht>
<app-opdracht [id]="2"></app-opdracht>
<app-opdracht [id]="3"></app-opdracht>

Answer Source

Use the safe-navigation operator to avoid errors when Angular evaluates the binding but async values have not yet arrived:

<p>{{ opdracht?.name }}</p>