1

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?

1
  • Which version are you using of Angular2? Commented Sep 25, 2016 at 18:52

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Tried this and get : core.umd.js:3464 ORIGINAL EXCEPTION: menuService is not defined
Sounds like you are missing an import for MenuService (like import {MenuService} from './menu.service')
@yurzui edited my answer and fixed some other issues I copied from your question - thanks!
Works! Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.