在打字稿中创建指令以在 angular 中显示加载进度

Create directive in typescript to show loading progress in angular

我正在尝试在 Typescript 中创建指令,它将监视未决的 $resource 请求。我只想要一个指令作为属性,它将与 index.html 中的 div 一起使用以显示加载进度。下面是我的指令代码。

module app.common.directives {

interface IProgressbarScope extends ng.IScope {
    value: number;
    isLoading: any;
    showEl: any;
}

class Progressbar implements ng.IDirective {

    static $inject = ['$http'];
    static instance(): ng.IDirective {
        return new Progressbar;
    }
    //transclude = true;
    restrict = 'A';
    replace = true;

    link = function (scope: IProgressbarScope, elements: ng.IAugmentedJQuery, attrs: ng.IAttributes, $http: ng.IHttpService) {

        debugger;
        scope.isLoading = function () {
            return $http.pendingRequests.length > 0;
        };
        scope.$watch(scope.isLoading, function (v) {
            debugger
           if (v) {
                elements.addClass("hidediv")
            } else {
                elements.removeClass("hidediv");
            }
        });
    }
}

angular.module('app')
    .directive('progressbar', Progressbar.instance);
}

在Index.html中的用法如下:

 <div progressbar id="myProcess" name="myProcess">
     // loading image
 </div>

但是在指令中,$http 总是未定义的。请注意,我没有直接使用 $http。我使用 $resource 服务发出服务器端 api 请求。

在 directiveController 中定义 $scope.isLoading 并从服务层进行 $http 调用。

基本controller.ts

export class sampleController {

    // inject service here  
    constructor() {

    }

    public isLoading() {
        callServiceFunction();
    }
}

sampleController.$inject['service'];

在自定义指令中导入此控制器。

SampleService.ts

export class sampleService {
  constructor() {


  }

}
sampleService.$inject = ['$http'];

在应用程序模块中注册此服务。

有关详细信息,请参阅 and large scale app architecture

$http 未定义的原因是,您试图从指令的 link 函数中获取 $http 依赖项。基本上 link 函数的第 4 个参数代表 require 控制器。

理想情况下,您应该从 Progressbar 构造函数中获取注入的依赖实例。

class Progressbar implements ng.IDirective {
    _http: ng.IHttpService; //defined _http variable
    static $inject = ['$http'];
    //asking for dependency here
    static instance($http: ng.IHttpService): ng.IDirective {
        this._http = $http; //get `$http` object assigned to `_http`
        return new Progressbar;
    }
    //transclude = true;
    restrict = 'A';
    replace = true;

    //removed dependency from here
    link = function (scope: IProgressbarScope, elements: ng.IAugmentedJQuery, attrs: ng.IAttributes) { 

        //use arrow function here
        scope.isLoading = ()=> {
            return this._http.pendingRequests.length > 0;
        };
        //use arrow function here
        scope.$watch(scope.isLoading, (v)=> {
           if (v) {
                elements.addClass("hidediv")
            } else {
                elements.removeClass("hidediv");
            }
        });
    }
}