我试图将我的指令转换为使用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
?
答案 0 :(得分:4)
当我进入我的成功功能时,它说无法读取未定义的属性'$ http'
这是因为您使用了function
:
function success(response) {
您可能打算使用()=>
(箭头功能)来保存this
上下文。
更多:https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html