SumLare SumLare - 14 days ago 4
TypeScript Question

Angular 2 can't get particular object

I have a simple API written in

Express
with the help of
MongoDB
, everything works fine except that my
Angular 2
can't get particular object. I can access list of objects, but when i try to get an object by
id
it returns me an error
ORIGINAL EXCEPTION: TypeError: Cannot read property 'name' of undefined
that means he can't get it. I believe that problem is that
id
property in
MongoDB
isn't a number, but it should so I can get that object.

My code below:

goal.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

import {
Goal ,
GoalService
} from '../shared/index';

@Component({
selector: 'my-goal',
moduleId: module.id,
templateUrl: 'goal.component.html',
styleUrls: ['goal.component.css'],
directives: [GoalComponent]
})

export class GoalComponent {
goal: Goal;
error: any;
private sub: any;

constructor(
private route: ActivatedRoute,
private router: Router,
private goalService: GoalService) {
}

ngOnInit() {
this.sub = this.route.params.subscribe(params => {
let id = +params['id'];
this.goalService.getGoal(id).then(goal => this.goal = goal);
});
}

ngOnDestroy() {
this.sub.unsubscribe();
}

}


goal.model.ts

export class Goal {
id: number;
name: string;
finish_date: Date;
}


goal.service.ts

import { Injectable } from '@angular/core';
import { Headers, Http, Response } from '@angular/http';

import '../../rxjs-operators';

import { Goal } from './goal.model';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class GoalService {

private goalsUrl = 'http://localhost:8081/api/goals';

constructor(private http: Http) { }

getGoals(): Promise<Goal[]> {
return this.http.get(this.goalsUrl)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}

getGoal(id: number) {
return this.getGoals()
.then(goals => goals.filter(goal => goal.id === id)[0]);
}

private extractData(res: Response) {
let body = res.json();
return body || { };
}

private handleError (error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Observable.throw(errMsg);
}

}


I tried to turn id into string and change it to _id, but no difference at all. So may be there are problems in something different, but it looks like id property is broken here.

Answer

I guess that the problem is within your template since the data of the particular element is loaded asynchronously.

You could try to use the Elvis operator. Something like this:

{{goal?.name}}