Rob Rob - 2 months ago 14
TypeScript Question

Angular2 access @Input from class inside constructor that calls a service

I am new to Angular2 and Typescript. I am trying to gain access to a @Input from the constructor in my class. A service is called from inside the constructor and I need to pass it an argument.

@Component({
selector:'side-menu',
templateUrl:'menu.html',
providers: [MenuService]
})

export class SideMenuComponent {
@Input() blockType;

menuItems

constructor(menuService:MenuService){
this.menuItems = menuService.getMenuItems(this.blockType); // Sends Undefined
this.menuItems = menuService.getMenuItems('HardCodedString'); //This works
}


}


and this is my Service

@Injectable()

export class MenuService {
getMenuItems(type) {
console.log(type)

switch(type){
case 'Thing':

return [];
break;
case 'Otherthing':
return [];
break;
default:
return [];


}

}
}


How can I ensure the @Input gets sent to the service?

Answer

Inputs are not yet set when the constructor is called. Move the constructor code to ngOnInit() instead.

@Component({
    selector:'side-menu',
    templateUrl:'menu.html',
    providers:    [MenuService]
 })

export class SideMenuComponent {
    @Input() blockType;

    menuItems

    constructor(private menuService:MenuService){}

    ngOnInit() {
        this.menuItems = this.menuService.getMenuItems(this.blockType); // Sends Undefined
        this.menuItems = this.menuService.getMenuItems('HardCodedString'); //This works
    }
}

Every time @Input()s are updated ngOnChanges() is called.
ngOnInit() is called after ngOnChanges() was called the first time.

Comments