簡體   English   中英

無法找出TypeScript錯誤TS2304:找不到名稱

[英]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指定變量范圍,例如varletconst

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM