Typescript writing a callable object

1.4k views Asked by At

I want to write a callable function in typescript.

Expected Javascript: -

app.factory('customLoader', function ($http, $q) {
    return function (options) {
        var deferred = $q.defer();
        var data = {
            'TEXT': 'Fooooo'
        };
        return deferred.resolve(data);
    };
});

My Solution in typescript.

    export interface LoadContent {
        (options:any):ng.IPromise<any>;
    }

    export function LoaderService($q:ng.IQService):LoadContent {
        return (options:any) => {
            var deferred = $q.defer();
            var data = {
                'TEXT': 'Fooooo'
            };
            deferred.resolve(data);
            return deferred.promise;
        }
    }
app.factory('customLoader', LoaderService);

I am planning to use angular.factory to initialize it. If I need to do the same thing in angular.service, how would I do this?

Also is there better way to write this using the typescript class?

1

There are 1 answers

1
basarat On BEST ANSWER

If I need to do the same thing in angular.service, how would I do this?

Just use a class

export class LoaderService {
    constructor(public $q:ng.IQService){        }
    getOptions(options:any) {
        var deferred = this.$q.defer();
        var data = {
            'TEXT': 'Fooooo'
        };
        deferred.resolve(data);
        return deferred.promise;
    }
}
app.service('customLoader', LoaderService);

More on this pattern : https://www.youtube.com/watch?v=Yis8m3BdnEM