Ich habe eine einfache API geschrieben in Express
mit Hilfe von MongoDB
, alles funktioniert gut, außer dass meine Angular 2
kann bestimmte Objekt nicht bekommen. Ich kann auf die Liste der Objekte zugreifen, aber wenn ich versuche, ein Objekt von id
zu bekommen, gibt es mir einen Fehler ORIGINAL EXCEPTION: TypeError: Cannot read property 'name' of undefined
zurück, das bedeutet, dass er es nicht bekommen kann. Ich glaube, dass das Problem ist, dass id
Eigentum in MongoDB
ist keine Nummer, aber es sollte, damit ich dieses Objekt bekommen kann.Angular 2 kann nicht bestimmte Objekt
Mein Code unten:
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);
}
}
Ich habe versucht, ID in Zeichenfolge umzuwandeln und es in _id ändern, aber keinen Unterschied. Es kann also sein, dass es Probleme in etwas anderem gibt, aber es sieht so aus, als wäre die ID-Eigenschaft hier kaputt.
Wow, ich habe das vergessen. Danke, es hat sehr geholfen. Ich habe den ganzen Code in '
' verpackt und jetzt funktioniert es. – SumLare