我遇到了一个关于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');
}
}
答案 0 :(得分:1)
视图将在异步observable返回任何值之前启动。在您的情况下,当CategoryComponent
被解雇时,categoryPosts
为undefined
。就在那时,您的视图还请求呈现undefined
属性的数据。
解决方案:您需要确保只有在您需要展示的内容时才会考虑那些需要categoryPosts
的DOM:
<ul *ngIf="categoryPosts && categoryPosts.posts">
<li *ngFor"let post of categoryPosts.posts">
{{ post.title }}
{{ post.body }}
</li>
</ul>