无法找出TypeScript错误TS2304:找不到名称

时间:2018-07-19 17:07:32

标签: angular typescript

我已使用以下代码通过此代码为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'.

任何人都可以帮忙。

1 个答案:

答案 0 :(得分:2)

有效地,您尝试通过其外观引用未声明的变量,该TypeScript将其视为错误。一种解决方案是,您可以初始化类属性loadedIngredient并在this这样的方法中用onSubmit()进行引用:

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);
   }    
}

或者您需要为var中的局部变量let指定变量范围,例如constloadedIngredientonSubmit()

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展示了错误/解决方案。

希望有帮助!