Angular 2 Observable订阅参数和服务错误

时间:2016-07-30 02:01:10

标签: angular rxjs angular2-routing

我遇到了一个关于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');
  }
}

1 个答案:

答案 0 :(得分:1)

视图将在异步observable返回任何值之前启动。在您的情况下,当CategoryComponent被解雇时,categoryPostsundefined。就在那时,您的视图还请求呈现undefined属性的数据。

解决方案:您需要确保只有在您需要展示的内容时才会考虑那些需要categoryPosts的DOM:

<ul *ngIf="categoryPosts && categoryPosts.posts">
  <li *ngFor"let post of categoryPosts.posts">
    {{ post.title }}
    {{ post.body }}
  </li>
</ul>