【问题标题】:Inject $http into TypeScript AngularJS Directive将 $http 注入 TypeScript AngularJS 指令
【发布时间】:2015-12-08 22:51:57
【问题描述】:

我正在尝试将我的指令转换为使用 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

【问题讨论】:

    标签: angularjs angularjs-directive typescript


    【解决方案1】:

    当我进入我的成功函数时,它显示无法读取未定义的属性 '$http'

    这是因为你使用了function

    function success(response) {
    

    您可能打算使用()=>(箭头函数),它会为您保留this 上下文。

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

    【讨论】:

    猜你喜欢
    • 2014-12-04
    • 1970-01-01
    • 2014-02-08
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多