将$ http注入TypeScript AngularJS指令

时间:2015-12-08 22:51:58

标签: angularjs angularjs-directive typescript

我试图将我的指令转换为使用TypeScript这是我目前所拥有的

'use strict';

module app.dashboard {       
    export class Safes implements ng.IDirective {

        static $inject = ['$log', '$http', 'storeFactory'];
        static instance($log, $http, storeFactory) {
            return new Safes($log, $http, storeFactory);
        }
        templateUrl = '/app/shared/mocks/table.html';
        restrict :string = 'A';
        scope: any = {
            title: '=',
            rows: '='
        };                
        link: (scope, element, attrs) => void;

        constructor(private $log, public $http: ng.IHttpProvider) {
            this.link = this._link.bind(this);
        }

        _link(scope, element, attrs) {
            this.storeFactory.getSafes().then(success, failure);

            function success(response) {
                scope.safes = response.data.safes;
                localStorage.setItem('safeCount', scope.safes.length);
                this.$http.get('/app/dashboard/safes/safes.html', { cache: this.$templateCache }).success(function (tplContent) {
                    element.replaceWith(this.$compile(tplContent)(scope));
                });
            }
        }
    }
    angular
        .module('app')
        .directive('safes', Safes.instance);
}

当我进入success函数时,它会显示Cannot read property '$http' of undefined

我做错了什么不能访问$http

1 个答案:

答案 0 :(得分:4)

  

当我进入我的成功功能时,它说无法读取未定义的属性'$ http'

这是因为您使用了function

function success(response) {

您可能打算使用()=>(箭头功能)来保存this上下文。

更多:https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html