SumLare SumLare - 1 year ago 128
Node.js Question

Angular 2 + Mongoose can't get particular object

I have a simple API written in

with the help of
, 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
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
property in
isn't a number, but it should so I can get that object.

My code below:


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

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

selector: 'my-goal',
templateUrl: 'goal.component.html',
styleUrls: ['goal.component.css'],
directives: [GoalComponent]

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

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() {



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


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';

export class GoalService {

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

constructor(private http: Http) { }

getGoals(): Promise<Goal[]> {
return this.http.get(this.goalsUrl)

getGoal(id: number) {
return this.getGoals()
.then(goals => goals.filter(goal => === 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';
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 Source

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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download