当我点击链接转到我的食谱页面时,在shopping-edit.component.ts中的ngOnDestroy方法中取消订阅时出现错误。这是图像
这是我的git 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 :(得分:2)
试试这个
{{1}}
答案 1 :(得分:0)
您必须将this.slService.startedEditing.subscribe()
的结果分配给this.subscription
答案 2 :(得分:0)
我修好了,愚蠢的错误。
在订阅之前在ngOnInit上定义this.subscription =
。
答案 3 :(得分:0)
由于类似的问题而打断,因为我在ngOnInit
期间无法订阅。
因此只需通过以下方式即可解决:
ngOnDestroy(): void {
if (this.subscription) {
this.subscription.unsubscribe();
}
}