【问题标题】:Angular2 access @Input from class inside constructor that calls a serviceAngular2从调用服务的构造函数中的类访问@Input
【发布时间】:2017-02-03 01:30:58
【问题描述】:

我是 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 被发送到服务?

【问题讨论】:

  • 你用的是哪个版本的Angular2?

标签: angular typescript


【解决方案1】:

调用构造函数时尚未设置输入。将构造函数代码移至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()s 时都会调用ngOnChanges()
在第一次调用ngOnChanges() 之后调用ngOnInit()

【讨论】:

  • 试过这个并得到:core.umd.js:3464 ORIGINAL EXCEPTION: menuService is not defined
  • 听起来您缺少MenuService 的导入(例如import {MenuService} from './menu.service'
  • @yurzui 编辑了我的答案并修复了我从您的问题中复制的一些其他问题 - 谢谢!
  • 有效!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-22
  • 1970-01-01
  • 2018-06-23
  • 2019-01-20
  • 2014-02-19
  • 1970-01-01
相关资源
最近更新 更多