TypeScript + AngularJS v1: Rewriting angular factory to TypeScript
Asked Answered
W

2

6

I am wondering how can I rewrite the following factory into a TypeScript code. Here is the original code:

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

So far I've tried the following:

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

But I get the following error:

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

Any ideas?

Wakerly answered 17/11, 2015 at 14:39 Comment(0)
A
2

I use this syntax:

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:

This is the snippet which I use to intercept $http calls (so it does work for me)

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);
}
Astylar answered 17/11, 2015 at 14:40 Comment(2)
It works, but throws me another error: "TypeError: Cannot read property 'reject' of undefined". Any idea? When I debug, it reads this.$q as undefined within the responseErrorWakerly
I extended my answer with a snippet I use to intercept $httpThaumatrope
S
-1

Use this core: 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;
}
}

Call:

this.userRolesService.GetUser()
Siderosis answered 18/11, 2015 at 7:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.