簡體   English   中英

TypeScript + AngularJS v1:將角度工廠重寫為TypeScript

[英]TypeScript + AngularJS v1: Rewriting angular factory to TypeScript

我想知道如何將以下工廠重寫為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.

有任何想法嗎?

我用這個語法:

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);

延伸:

這是我用來攔截$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);
}

使用此核心: 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM