Angular 2无法获得特定对象

时间:2016-07-05 10:50:21

标签: angular typescript

我在Express的帮助下使用MongoDB编写了一个简单的API,除了我的Angular 2无法获取特定对象外,一切正常。我可以访问对象列表,但是当我尝试通过id获取对象时,它会返回错误ORIGINAL EXCEPTION: TypeError: Cannot read property 'name' of undefined,这意味着他无法获取它。我认为问题是id中的MongoDB属性不是数字,但我应该这样做。

我的代码如下:

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);
  }

}

我试图将id转换为字符串并将其更改为_id,但完全没有区别。所以可能存在不同的问题,但看起来id属性在这里被打破了。

1 个答案:

答案 0 :(得分:1)

我猜这个问题在你的模板中,因为特定元素的数据是异步加载的。

您可以尝试使用Elvis运算符。像这样:

{{goal?.name}}