Reputation: 531
I get this error when I try to use create new instance of a Class with parameters, but when not using parameters it works fine. What can be the problem?
Here is the class
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;
}
}
Here is the component
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() {
}
}
if instead I do this in recipe.ts and recipe-list.component.ts respectively:
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() {
}
}
works perfectly.
Upvotes: 2
Views: 3934
Reputation: 55443
The problem should be with this keyword
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
}
UPDATE: I just tested this and works perfectly.
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);
}
....
}
NOTE. remove providers:[Recipe]
(no need of that). You just need to import it wherever you want to use it which you are already doing.
Update1: I have tested it with plunker too and its working,
DEMO : https://plnkr.co/edit/Vxdeyjwdjol9TnVhCV19?p=preview check browser's console.
Upvotes: 3