我正在缓慢地建立一个angular2网站,但是我对这个平台仍然缺乏经验。现在,我有两个使用相同服务的组件:stories和storyDe​​tails。故事组件仅从我的Web API获取所有故事的列表。 storyDe​​tails组件将列出有关单个故事的更多详细信息。故事组件工作正常,但是当我尝试加载storyDe​​tails组件时出现错误。

Uncaught (in promise): Error: Error in /app/stories/details/storyDetails.component.template.html:0:22 caused by: Cannot read property 'title' of undefined

我已经在服务的extractData函数上断点了,并验证了是否返回了json并具有以下值:body = Object {storyId: 1, urlAffix: "a_story_title", title: "A Story Title", text: "This is the story", entityId: null…}但是,应该指出的是,在执行此行之前我遇到了错误。

以下是相关文件:

storyService.service.ts

import {Injectable} from '@angular/core';
import {Story} from '../story';
import { Http, Response } from '@angular/http';
import { Observable }     from 'rxjs/Observable';

@Injectable()
export class StoryService {
    private storyUrl = 'http://localhost:51332/api/storyapi';  // URL to web API
    constructor(private http: Http) { }
    getStories(): Observable<Story[]> {
        return this.http.get(this.storyUrl)
            .map(this.extractData)
            .catch(this.handleError);
    }
    getStoryDetails(storyId: Number): Observable<Story> {
        return this.http.get(`${this.storyUrl}/${storyId}`)
            .map(this.extractData)
            .catch(this.handleError);
    }
    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); // log to console instead
        return Observable.throw(errMsg);
    }
}


storyDe​​tails.component.ts

import { Component } from '@angular/core';
import { OnInit } from '@angular/core';

import { Story } from '../story.ts';
import { StoryService } from '../services/storyService.service';

import { ActivatedRoute } from '@angular/router';

@Component({
    selector: 'storyDetails',
    templateUrl: '/app/stories/details/storyDetails.component.template.html',
    providers: [StoryService]
})

export class StoryDetails implements OnInit {
    errorMessage: string;
    story: Story;
    mode = 'Observable';
    storyId: Number;
    private sub: any;
    constructor(private storyService: StoryService, private route: ActivatedRoute) { }
    ngOnInit() {

        this.route.params.subscribe(params => {
            this.storyId = +params['id']; // (+) converts string 'id' to a number
            this.getStoryDetails(this.storyId);
        });
    }
    getStoryDetails(storyId : Number) {
        this.storyService.getStoryDetails(storyId)
            .subscribe(
            story => this.story = story,
            error => this.errorMessage = <any>error);
    }
    ngOnDestroy() {
        this.sub.unsubscribe();


  }
}


storyDe​​tails.component.template.html

<h2>Story Details</h2>


{{story.title}}


故事

export class Story {
    public storyId: Number;
    public urlAffix: string
    public title: string;
}


我注意到,如果我未在引用该故事对象的html模板文件中放置任何内容,则不会收到该错误。我确定我犯了一个菜鸟错误,但我找不到它。

最佳答案

storyDe​​tails组件正在尝试在定义之前渲染{{story.title}}。尝试将组件包装或仅将标题包装在* ngIf中。异步调用完成(并定义了故事)后,跨度将与标题一起呈现。

<span *ngIf="story">
    {{story.title}}
</span>

10-07 21:30