Angular 2:无法读取未定义的属性'unsubscribe'

时间:2017-03-26 09:47:07

标签: angular unsubscribe

这是一个基于Angular 2构建的电子商务购物车。当我离开此组件并加载任何其他组件时,我收到错误

  

EXCEPTION:未捕获(在承诺中):错误:./ProductsComponent中出错   class ProductsComponent - 内联模板:11:4引起:无法读取   属性'unsubscribe'未定义

我尝试删除私人订阅:订阅和ngOnDestroy。但仍然会得到同样的错误。

  import { Component, OnInit, OnDestroy } from '@angular/core';
  import { Products } from './products';
  import { PRODUCTS } from './product_list';
  import { Subscription } from 'rxjs/Rx';
  import { PaginationService } from './pagination.service';
  import { Pagination } from './pagination';
  import 'rxjs/add/operator/switchMap';

  @Component({
    selector: 'any-products',
    templateUrl: './products.component.html',
    styleUrls: ['./products.component.css']
  })

  export class ProductsComponent implements OnInit, OnDestroy {

    color: string;
    allProducts = PRODUCTS;
    private subscription: Subscription;
    paginationNow : Pagination = this.paginationService.CreatePaginationNow(this.paginationService.productPerPage);
    products : Array<Products> = this.allProducts.slice((this.paginationNow.paginationLowerLimit-1),this.paginationNow.paginationHigherLimit); 

    constructor( private paginationService : PaginationService ) { }

    ngOnInit() {
      this.subscription = this.paginationService.pushedPagination.subscribe(
        PaginationNow => {
          this.paginationNow = PaginationNow;
           this.products = this.allProducts.slice((this.paginationNow.paginationLowerLimit-1),this.paginationNow.paginationHigherLimit);
        }        
      );      
    }

    ngOnDestroy(){
        this.subscription.unsubscribe();
    }
  }

enter image description here

1 个答案:

答案 0 :(得分:0)

我解决了这个问题。

&#34; ProductsComponent - 内联模板:11:4&#34;

我一直在寻找Product Component订阅的问题,但真正的问题是在这里未提供的Product Component的子组件。

Product Component of product Component(pagination.component.ts)的问题是:

ngOnInit() {
     this.paginationService.pushedPagination.subscribe(
        PaginationNow => {
          this.paginationNow = PaginationNow;       
        }
      ); 

   ngOnDestroy() {
    this.subscription.unsubscribe();
  }

我改变了是:

  ngOnInit() {    
     this.subscription = this.paginationService.pushedPagination
        .subscribe(
               PaginationNow => {
                    this.paginationNow = PaginationNow;       
                }
          );

由于我对Angular 2故障排除的经验不足。 (内联模板:11:4)