TypeScript + AngularJS v1:将角度工厂重写为TypeScript

时间:2015-11-17 14:39:39

标签: angularjs typescript interceptor angularjs-factory

我想知道如何将以下工厂重写为TypeScript代码。这是原始代码:

app.factory('errorInterceptor', function ($q) {
    return {
        responseError: function (response) {
            console.error("Error: " + response.statusText);
            return $q.reject(response);
        }
    }
});

到目前为止,我已经尝试了以下内容:

 export class errorInterceptor {
    constructor(private $q:ng.IQService) {

    }

    public responseError(response:any){
        console.error("Error: " + response.statusText);

        return this.$q.reject(response);
    }

    public static getFactory(){
        return  errorInterceptor;
    }
}

app.factory('errorInterceptor',errorInterceptor.getFactory());

但是我收到以下错误:

Provider 'errorInterceptor' must return a value from $get factory method.

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

我使用这种语法:

export class errorInterceptor {
    // to support minification
    static $inject = ["$q"];

    constructor(private $q:ng.IQService) {

    }

    public responseError(response:any){
        console.error("Error: " + response.statusText);

        return this.$q.reject(response);
    }

    //public static getFactory(){
    //    return  errorInterceptor;
    //}
}

//app.factory('errorInterceptor',errorInterceptor.getFactory());
app.service('errorInterceptor',errorInterceptor);

EXTEND:

这是我用来拦截$http来电的代码段(因此它对我有效)

module MyModule
{
    var app = angular.module("MyModule");

    export class HttpErrorAspect
    {
        static $inject = ["$q"];

        constructor(private $q: ng.IQService)
        {
        }

        public responseError = (rejection: any): any =>
        {
            // do some magic, e.g. use toaster or alerter
            // to notify about the issue
            ...

            // reject that all
            return this.$q.reject(rejection);
        }
    }

    app.service("HttpErrorFilter", MyModule.HttpErrorAspect);
}

答案 1 :(得分:-1)

使用此核心: https://github.com/aleksey-pastuhov/AngularJS-Typed-Core/blob/master/AngularJSTypedCore/Script/service.ts

@service(app)
export class UserRolesService {
static $inject: string[] = ["$cookies"];

private $cookies: angular.cookies.ICookiesService;

user: IUser;

GetUser(): IUser {
    return this.user;
}
}

呼叫:

this.userRolesService.GetUser()