2015-10-20 92 views
-1

我想我有一个范围问题与JS。请看下面我的代码。 这是我在es6中的AngularJS示例。我使用grunt browserify将代码编译为es5。ES6 AngularJS指令<>服务通信

如果我打电话给我的例子,我得到了错误:在ChainsDirective.loadChains [如chainsServiceLoadChains]

我检查一下,并找出在这 this.gatewayServiceGet不是一个函数 : 类型错误加载链接是不一样的这个比在构造函数。

我该怎么办?

这是我app.js

'use strict'; 

import AppController from './appController.js'; 
import ChainsDirective from './components/chains/chains.directive.js'; 
import ChainsService from './components/chains/chains.service.js'; 
import GatewayService from './components/common/gateway/gateway.service.js'; 

angular 
    .module('SalesCockpit', ['ui.router', 'ui.grid']) 
    .config($stateProvider => { 
     $stateProvider 
      .state('chains', { 
       url: '/chains', 
       templateUrl: 'components/chains/chains.html' 
      }) 
      .state('chainDetail', { 
       url: '/chain/{chainId:int}/detail', 
       templateUrl: 'components/chain-detail/chain-detail.html' 
      }) 
     ; 

    }) 
    .controller('AppController', AppController) 
    .service('chainsService', ChainsService) 
    .service('gatewayService', GatewayService) 
    .directive('chains', ChainsDirective); 

这是我的锁链指令

export default function ChainsDirective() { 
    class ChainsDirective { 

     /*@ngInject*/ 
     constructor(chainsService, $state) { 
      this.chainsServiceLoadChains = chainsService.loadChains; 
      this.gridOptions = { 
       enableColumnMenus: false, 
       columnDefs: [ 
        { 
         name: 'id', 
         visible: false 
        }, 
        { 
         name: 'name', 
         displayName: 'Kette', 
         cellTemplate: '<div class="ui-grid-cell-contents"><a ng-click="grid.appScope.openDetail(row.entity.id)">{{row.entity.name}}</a></div>' 
        } 
       ] 
      }; 
      this.$stateGo = $state.go; 
      this.fetch(); 
     } 

     /** 
     * @param int chainId 
     */ 
     openDetail(chainId) { 
      this.$stateGo('chainDetail', {chainId}) 
     } 

     fetch() { 
      return this.chainsServiceLoadChains().then(data => { 
       this.gridOptions.data = data 
      }) 
     } 
    } 

    return { 
     restrict: 'E', 
     template: '<div id="chains" ui-grid="gridOptions" external-scopes="$scope" class="grid"></div>', 
     controller: ChainsDirective, 
     controllerAs: 'chains' 
    } 
} 

这是我的链役

export default class ChainsService { 

    /*@ngInject*/ 
    constructor(gatewayService) { 
     this.gatewayServiceGet = gatewayService.get; 
    } 

    /** 
    * @returns Promise 
    */ 
    loadChains() { 
     return this.gatewayServiceGet('loadChains'); 
    } 
} 
+0

我假设代码正在交叉编译和像边缘不跑了。你能发布翻译的代码吗?我对课程如何翻译特别感兴趣。 –

回答

1

FWIW,这有什么好做的ECMAScript JavaScript一直以这种方式工作。


this的值取决于函数是如何。所以,如果你把它作为

this.chainsServiceLoadChains() 

thischainsServiceLoadChains会参考什么是.,这是this是指ChainsDirective实例之前。

一个解决办法是绑定this值的函数为特定值:

this.chainsServiceLoadChains = chainsService.loadChains.bind(chainsService); 

现在,它不再重要的功能是如何调用,this总是引用chainsService

了解更多关于this

相关问题