m44rt3np44uw m44rt3np44uw - 1 month ago 19
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?

Thanks,

Maarten

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


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>

Answer

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

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