I'm struggling to pass data from an Angular service to a component. I start with a simple model class (./cet.model)
export class CetModel {
constructor(
public waferDiameter: number = 10
) {}
}
Then define an angular service (./cet.service);
import { CetModel } from './cet.model';
export class CetService {
private cet: CetModel;
getCet() {
return this.cet;
}
}
And the associated angular component;
import { Component } from '@angular/core';
import { CetService } from './cet.service';
import { CetModel } from './cet.model';
@Component({
selector: 'cet-input',
templateUrl: './cet-input.component.html',
providers: [ CetService ]
})
export class CetInputComponent {
constructor(public cetService: CetService){}
cet: CetModel = this.cetService.getCet();
waferDiameter = this.cet.waferDiameter
}
The code builds without errors, but when I try to display the variable 'waferDiameter' in the component's template I receive the error;
"Cannot read property 'waferDiameter' of undefined".
Where am I going wrong?
Thanks
Change your code in cet.service as follows :
import { CetModel } from './cet.model';
export class CetService {
private cet = new CetModel();
getCet() {
return this.cet;
}
}
You have not created the model object. That's why this.cet
returns undefined and you get waferDiameter
undefined.