我遇到了一个关于Observable的问题,它同时订阅了路由参数和服务(在我看来)。我在视图上看到错误
无法读取未定义的属性“帖子”
虽然我可以记录帖子数据。请帮助我解决此问题。提前致谢!
category.component.ts
@Component({
// moduleId: module.id,
selector: 'category',
templateUrl: 'category.component.html',
providers: [HTTP_PROVIDERS],
directives: [ROUTER_DIRECTIVES]
})
export class CategoryComponent implements OnInit {
private category: string;
private type: string;
private paramsSub: any;
categoryPosts: CategoryPosts;
constructor(
private route: ActivatedRoute,
private categoryService: CategoryService
) {}
ngOnInit() {
this.paramsSub = this.route.params.subscribe(params => {
this.category = params['category'];
this.type = params['type'];
this.categoryService.getPostInCategory(this.category, this.type)
.subscribe((categoryPosts: CategoryPosts) => {
this.categoryPosts = categoryPosts;
console.log(this.categoryPosts.posts) // can print the data
},
error => {
console.log(error);
});
});
}
// ngOnDestroy(){
// this.paramsSub.unsubscribe();
// }
}
category.component.html
<ul>
<li *ngFor"let post of categoryPosts.posts | async">
{{ post.title }}
{{ post.body }}
</li>
</ul>
category.services.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { CategoryPosts } from './index';
import * as global from '../shared/global/globals';
@Injectable()
export class CategoryService {
private _baseUrl: string = '';
constructor(private http: Http) {
this._baseUrl = global.BASE_URL;
}
getPostInCategory(category: string, type: string) : Observable<CategoryPosts>{
return this.http.get(this._baseUrl + 'category/' + category + '/' + type)
.map((res: Response) => {
return res.json();
})
.catch(this.handleError);
}
private handleError(error: any) {
var applicationError = error.headers.get('Application-Error');
var serverError = error.json();
var modelStateErrors: string = '';
if (!serverError.type) {
console.log(serverError);
for (var key in serverError) {
if (serverError[key])
modelStateErrors += serverError[key] + '\n';
}
}
modelStateErrors = modelStateErrors = '' ? null : modelStateErrors;
return Observable.throw(applicationError || modelStateErrors || 'Server error');
}
}
在从异步可观察对象返回任何值之前,将启动视图。就您而言,当您CategoryComponent
被解雇时,categoryPosts
是undefined
。就在那时,您的视图还请求undefined
渲染该属性的数据。
解决方案:您需要确保categoryPosts
仅当您要显示以下内容时,才考虑那些需要您的DOM :
<ul *ngIf="categoryPosts && categoryPosts.posts">
<li *ngFor"let post of categoryPosts.posts">
{{ post.title }}
{{ post.body }}
</li>
</ul>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句