当我尝试使用带参数的类创建新实例时,我收到此错误,但是当不使用参数时,它可以正常工作。可能是什么问题?
这是班级
export class Recipe {
public name: string;
public description: string;
public imageP: string;
constructor(name1: string, description1: string, imagePath1: string) {
this.name = name1;
this.description = description1;
this.imageP = imagePath1;
}
}
这是组件
import {Component, OnInit, Output} from '@angular/core';
import { Recipe } from '../recipe';
@Component({
selector: 'rb-recipes-list',
templateUrl: './recipes-list.component.html',
providers: [ Recipe ]
})
export class RecipesListComponent implements OnInit {
theRecipe: Recipe = new Recipe( 'New', 'blah blah blah', 'ddkkkiskxmdks');
recipe = this.theRecipe.name;
constructor() { }
ngOnInit() {
}
}
如果我分别在recipe.ts和recipe-list.component.ts中这样做:
export class Recipe {
public name: string = 'hello world';
public description: string = 'hello world';
public imageP: string = 'hello world';
}
import {Component, OnInit, Output} from '@angular/core';
import { Recipe } from '../recipe';
@Component({
selector: 'rb-recipes-list',
templateUrl: './recipes-list.component.html',
providers: [ Recipe ]
})
export class RecipesListComponent implements OnInit {
//recipes: Recipe[] = [];
theRecipe: Recipe = new Recipe()
recipe = this.theRecipe.name;
constructor() { }
ngOnInit() {
}
}
完美无缺。
答案 0 :(得分:3)
问题应该是此关键字
export class RecipesListComponent implements OnInit {
theRecipe: Recipe = new Recipe( 'New', 'blah blah blah', 'ddkkkiskxmdks');
// recipe = this.theRecipe.name; //<<<===removed this line
recipe = theRecipe.name; //<<===removed this keyword
}
更新:我刚刚对此进行了测试,效果很好。
export class RecipesListComponent implements OnInit {
theRecipe:Recipe;
constructor(){
this.theRecipe = new Recipe( 'New', 'blah blah blah', 'ddkkkiskxmdks');
console.log(this.theRecipe.name);
}
....
}
OR
export class RecipesListComponent implements OnInit {
theRecipe:Recipe;
theRecipe = new Recipe( 'New', 'blah blah blah', 'ddkkkiskxmdks');
constructor(){
console.log(this.theRecipe.name);
}
....
}
注意即可。删除providers:[Recipe]
(不需要)。你只需要导入它就可以在你想要的地方使用它。
Update1 :我已经使用plunker对其进行了测试并且正常运行,
DEMO:https://plnkr.co/edit/Vxdeyjwdjol9TnVhCV19?p=preview 检查浏览器的控制台。