[英]Cannot figure out TypeScript error TS2304: Cannot find name
我已經使用以下代碼通過此代碼分配了loadedIngredient
對象。
我使用的代碼是
import { Component, OnInit, ViewChild, ElementRef, EventEmitter, Output } from '@angular/core';
import { Ingredient } from '../../shared/Ingredient.model';
@Component({
selector: 'app-shopping-list-edit',
templateUrl: './shopping-list-edit.component.html',
styleUrls: ['./shopping-list-edit.component.css']
})
export class ShoppingListEditComponent implements OnInit {
@ViewChild('name') ingredientName:ElementRef;
@ViewChild('amount') ingredientAmount:ElementRef;
@Output() inputValue = new EventEmitter<Ingredient>();
constructor() { }
ngOnInit() {
}
onSubmit(){
const iname = this.ingredientName.nativeElement.value;
const iamount = this.ingredientAmount.nativeElement.value;
loadedIngredient:Ingredient = new Ingredient(iname,iamount);
this.inputValue.emit(loadedIngredient);
}
}
不斷彈出的錯誤是。
ERROR in src/app/shopping-list/shopping-list-edit/shopping-list-edit.component.t s(21,4): error TS7028: Unused label. src/app/shopping-list/shopping-list-edit/shopping-list-edit.component.ts(21,21): error TS2539: Cannot assign to 'Ingredient' because it is not a variable. src/app/shopping-list/shopping-list-edit/shopping-list-edit.component.ts(22,25): error TS2304: Cannot find name 'loadedIngredient'.
誰能幫忙。
實際上,您試圖通過其外觀引用未聲明的變量,該TypeScript將其視為錯誤。 一種解決方案是,您可以初始化類屬性loadedIngredient
並在諸如onSubmit()
方法中this
進行引用:
import { Component, OnInit, ViewChild, ElementRef, EventEmitter, Output } from '@angular/core';
import { Ingredient } from '../../shared/Ingredient.model';
@Component({
selector: 'app-shopping-list-edit',
templateUrl: './shopping-list-edit.component.html',
styleUrls: ['./shopping-list-edit.component.css']
})
export class ShoppingListEditComponent implements OnInit {
@ViewChild('name') ingredientName:ElementRef;
@ViewChild('amount') ingredientAmount:ElementRef;
@Output() inputValue = new EventEmitter<Ingredient>();
loadedIngredient: Ingredient;
constructor() { }
ngOnInit() {}
onSubmit(){
const iname = this.ingredientName.nativeElement.value;
const iamount = this.ingredientAmount.nativeElement.value;
this.loadedIngredient: Ingredient = new Ingredient(iname, iamount);
this.inputValue.emit(this.loadedIngredient);
}
}
或者,您需要為onSubmit()
的局部變量loadedIngredient
指定變量范圍,例如var
, let
, const
:
onSubmit(){
const iname = this.ingredientName.nativeElement.value;
const iamount = this.ingredientAmount.nativeElement.value;
const loadedIngredient: Ingredient = new Ingredient(iname, iamount);
this.inputValue.emit(this.loadedIngredient);
}
感謝慷慨的@lealceldeiro,這里有一個StackBlitz演示了錯誤/解決方案。
希望有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.