2015-10-20 52 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