2017-05-25 105 views
0

我正在研究一个函数,有人可以给出关于如何指定一个函数外面的函数的建议吗? 在if语句中我想调用otherfunction()。Angular 2:Ts:嵌套函数

@Injectable() 
export class menuService { 
    constructor(){} 
    testing(){ console.log('something')} 
    loadwidget(){ 


      // not able to call this function 
      this.testing() 

    } 
} 

错误,我得到的是“this.testing是不是一个函数”

ERROR TypeError: this.testing is not a function 
    at Object.menuService.loadwidget (http://localhost:3000/main.bundle.js:755:14) 
    at Object.eval [as handleEvent] (ng:///AppModule/tbuttonsComponent.ngfactory.js:36:41) 
    at handleEvent (http://localhost:3000/vendor.dll.js:13146:138) 
    at callWithDebugContext (http://localhost:3000/vendor.dll.js:14354:42) 
    at Object.debugHandleEvent [as handleEvent] (http://localhost:3000/vendor.dll.js:13942:12) 
    at dispatchEvent (http://localhost:3000/vendor.dll.js:10121:21) 
    at http://localhost:3000/vendor.dll.js:10711:38 

https://plnkr.co/edit/XCHsu19UhR9wWxz4VLOx?p=preview

回答

1

这正是你应该如何在类中访问其他方法,关闭this关键字。如果您正在使用上面的课程,那么问题是没有在customfunction()中的任何位置定义,因此错误。因此,otherfunction()中的console.log()声明永远不会有机会运行。

编辑:我看了一下你添加的Plunker,结果证明这是一个范围问题。我更新了menuService类,则使用箭头功能隐式绑定thismenuService,第三个按钮开始按预期工作:

export class menuService { 
    constructor(){ 
    // I moved this into the constructor and updated loadingwidget below 
    this.menu = [{ 
     id: 1, 
     loadingwidget:() => { this.loadwidget(); }, 
    }]; 
    } 

    testing(){ 
    console.log('something'); 
    alert('something'); 
    } 

    loadwidget(){ 
    this.testing(); 
    } 
} 

这是你Plunker的工作版本:https://plnkr.co/edit/sF08cccRb2b0xkfTspVV?p=preview

+0

难道因为它是注射剂吗? –

+0

@ChrisTarasovs看看我的编辑,这不是一个@injectable问题,这是'this'没有绑定到'menuService'的问题。 – IAmKale

0

你如何定义应该工作。如果otherfunction()未被调用,请检查您是否有语句,也许比较不会返回您所期望的内容。

请看看这个plunker例如:https://plnkr.co/edit/4MWYDdeS5cCTDHI64HO2?p=preview

+0

我已经完全更新了我的方式,我得到它不是一个函数,但我正确地调用它。 –

+0

我已经更新了也在使用您的代码的plunker示例。你会比较你的代码?还请看看你在哪里调用loadwidget()。 – hakany

+0

这里更接近我明智的代码:https://plnkr.co/edit/XCHsu19UhR9wWxz4VLOx?p=preview –

0

这是因为注射的不是和你不需要注射也因为你没有任何东西注射到服务。所以你可以省略。但我可以看到有像这一个码数问题,

menu = [ 
     { 
     id = 1, 
     loadingwidget: this.loadwidget 
     } 
    ] 

,它应该是

menu = [ 
     { 
     id:1, 
     loadingwidget: this.loadwidget 
     } 
    ] 

,它是不正确编译。它工作得很好。