Im new to Angular2 and right now I'm trying to build a simple app that displays a list of objects. From there I want click through to a detailed view of one object. When I do so and want to access one of the objects' properties I get an exception:
cannot read property 'id' of undefined
This is the code I'm using:
my service looks like this (based on the tutorial found on the angular site):
getQuotation(id: number): Observable<Quotation> {
return this.http.get(this.quotationUrl)
.map(this.extractData)
.catch(this.handleError);
};
private extractData(res: Response) {
return res.json();
}
private handleError (error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
return Observable.throw(errMsg);
}
The http.get call points to a static json file that looks like this:
{
"id": 1,
"name": "string",
"email": "string",
"date": "string",
"quotationStatus": "string",
"read": true
}
and seems loaded correctly if I write the res.json() to the console.
The quotation component:
import { Component, OnInit } from '@angular/core'; import {QuotationService} from "./quotation.service";
@Component({
templateUrl: './quotation.component.html',
styleUrls: ['./quotation.component.css'],
providers: [QuotationService]
}) export class QuotationComponent implements OnInit {
constructor(private quotationService : QuotationService) { }
quotation : Quotation;
errorMessage : string;
ngOnInit() {
this.quotationService.getQuotation(1)
.subscribe(
quotation => this.quotation = quotation,
error => this.errorMessage = <any>error,
);
}
}
export class Quotation {
id: number;
name: string;
email: string;
date: string;
quotationStatus: string;
read: boolean;
}
And the template looks like this:
<div>
<div class="row">
<div class="columns small-12">
<h1>Offerte # {{ quotation.id }}</h1>
</div>
</div>
...
</div>
If I leave out the {{ quotation.id }} part the template is loaded without any error.
Any help would be appreciated since this is already taking too much time to fix and I'm starting to get frustrated :).
EDIT
Just to be clear. I don't want to hide the exception, I want the quotation to be loaded and have to understand why it is not right now.
try this:-
<div class="columns small-12">
<h1>Offerte # {{ quotation?.id }}</h1>
</div>