Angular2从调用服务的构造函数中的类访问@Input

时间:2016-09-25 18:35:32

标签: angular typescript

我是Angular2和Typescript的新手。我试图从我的类中的构造函数访问@Input。从构造函数内部调用一个服务,我需要传递一个参数。

@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
    }


}

这是我的服务

    @Injectable()

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

        switch(type){
            case 'Thing':

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


        }

    }
}

如何确保@Input被发送到服务?

1 个答案:

答案 0 :(得分:2)

调用构造函数时尚未设置输入。将构造函数代码移动到ngOnInit()

@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
    }
}

每次更新@Input()时,都会调用ngOnChanges() 在第一次调用ngOnInit()后调用ngOnChanges()