2017-07-03 103 views
0

我在我的shopping-edit.component.ts中的ngOnDestroy方法中取消訂閱時收到錯誤,當我單擊鏈接去我的食譜頁面。這裏是圖像ngOnDestroy Uncaught(承諾):TypeError:無法讀取未定義的屬性'取消訂閱'

error on link click

這裏是我的混帳https://github.com/CHBaker/First-Angular-App

一個鏈接,我的代碼片段:

import { 
    Component, 
    OnInit, 
    OnDestroy, 
    ViewChild 
} from '@angular/core'; 
import { NgForm } from '@angular/forms'; 
import { Subscription } from 'rxjs/Subscription'; 


import { Ingredient } from '../../shared/ingredient.model'; 
import { ShoppingListService } from '../shopping-list.service'; 

@Component({ 
    selector: 'app-shopping-edit', 
    templateUrl: './shopping-edit.component.html', 
    styleUrls: ['./shopping-edit.component.css'] 
}) 
export class ShoppingEditComponent implements OnInit, OnDestroy { 
    @ViewChild('f') slForm: NgForm; 
    subscription: Subscription; 
    editMode = false; 
    editedItemIndex: number; 
    editedItem: Ingredient; 

    constructor(private slService: ShoppingListService) { } 

    ngOnInit() { 
     this.slService.startedEditing 
      .subscribe(
       (index: number) => { 
        this.editedItemIndex = index; 
        this.editMode = true; 
        this.editedItem = this.slService.getIngredient(index); 
        this.slForm.setValue({ 
         name: this.editedItem.name, 
         amount: this.editedItem.amount 
        }) 
       } 
      ); 
    } 

    onSubmit(form: NgForm) { 
     const value = form.value; 
     const newIngredient = new Ingredient(value.name, value.amount); 
     if (this.editMode) { 
      this.slService.updateIngredient(this.editedItemIndex, newIngredient); 
     } else { 
      this.slService.addIngredient(newIngredient); 
     } 
     this.editMode = false; 
     form.reset(); 
    } 

    onClear() { 
     this.slForm.reset(); 
     this.editMode = false; 
    } 

    onDelete() { 
     this.slService.deleteIngredient(this.editedItemIndex); 
     this.onClear(); 
    } 

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

你是否100%確定這個.subscription實際上包含一個Subscription對象? –

回答

1

試試這個

this.subscription = this.slService.startedEditing 
     .subscribe(
      (index: number) => { 
       this.editedItemIndex = index; 
       this.editMode = true; 
       this.editedItem = this.slService.getIngredient(index); 
       this.slForm.setValue({ 
        name: this.editedItem.name, 
        amount: this.editedItem.amount 
       }) 
      } 
     ); 
0

必須的this.slService.startedEditing.subscribe()結果分配給this.subscription

0

我修好了,愚蠢的錯誤。

在訂閱之前在ngOnInit上定義this.subscription =

相關問題