[英]Getting error when using observables with an http service in Angular2: Cannot read property '[property]' of undefined
I'm slowly building an angular2 site, but I'm very inexperienced with this platform still. 我正在缓慢地建立一个angular2网站,但是我对这个平台仍然缺乏经验。 Right now I have two components that use the same service: stories and storyDetails.
现在,我有两个使用相同服务的组件:stories和storyDetails。 The stories component just gets a list of all stories from my web api.
故事组件仅从我的Web API获取所有故事的列表。 The storyDetails component will list more detailed information about a single story.
storyDetails组件将列出有关单个故事的更多详细信息。 The stories component works fine, but I am getting an error when I try to load the storyDetails component.
故事组件工作正常,但是当我尝试加载storyDetails组件时出现错误。
Uncaught (in promise): Error: Error in /app/stories/details/storyDetails.component.template.html:0:22 caused by: Cannot read property 'title' of undefined
I've breakpointed on my service's extractData function and verified that json is being returned and has the following value: body = Object {storyId: 1, urlAffix: "a_story_title", title: "A Story Title", text: "This is the story", entityId: null…}
However, it should be noted that I'm getting the error before this line is ever executed. 我在服务的extractData函数上断点了,并验证了是否返回了json并具有以下值:
body = Object {storyId: 1, urlAffix: "a_story_title", title: "A Story Title", text: "This is the story", entityId: null…}
但是,应该注意的是,在执行此行之前,我会收到错误消息。
Here are the relevant files: 以下是相关文件:
storyService.service.ts 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);
}
}
storyDetails.component.ts storyDetails.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();
}
}
storyDetails.component.template.html storyDetails.component.template.html
<h2>Story Details</h2>
{{story.title}}
story.ts 故事
export class Story {
public storyId: Number;
public urlAffix: string
public title: string;
}
I noticed that if I don't put anything in the template html file that references the story object, I don't get the error. 我注意到,如果我未在引用该故事对象的html模板文件中放置任何内容,则不会收到该错误。 I'm sure I'm making a rookie mistake but I just cannot find it.
我确定我犯了一个菜鸟错误,但我找不到它。
The storyDetails component is trying to render {{story.title}} before it is defined. storyDetails组件正在尝试在定义之前渲染{{story.title}}。 Try wrapping your component or just the title in an *ngIf.
尝试将组件包装或仅将标题包装在* ngIf中。 Once the asynchronous call is complete (and story is defined) the span will render along with the title.
异步调用完成(并定义了故事)后,跨度将与标题一起呈现。
<span *ngIf="story">
{{story.title}}
</span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.