Alan2
Alan2

Reputation: 24562

Using Typescript can I create a service in more compact way?

My code looks like this:

app.factory('utilityService', [
    '$http',
    '$angularCacheFactory',
    utilityService
]);

function utilityService(
    $http,
    $angularCacheFactory
    ) {

    var factory: {
        rowClicked($index, collection);
    } = <any>{};

    factory.rowClicked = function ($index, collection) {
        var row = collection[$index];
        if (row.current) {
            row.current = false;
            return null;
        } else {
            collection.forEach(function (object) {
                object.current = false;
            });
            row.current = true;
            return $index;
        }
    };

    return factory;

}

Is there a way I can combine the definition and code something like this:

    var factory2: {

        rowClicked: ($index, collection) => { ... };

    }

    return factory2;

Note that I did try the code above but I think I'm not on the right track as I saw many typescript related errors.

Upvotes: 0

Views: 173

Answers (1)

PSL
PSL

Reputation: 123739

You can define an interface for your service instead and keep it external to your service. So you can summarize this as :-

export interface IUtilityService {

    /**
     * Returns ...
     * @param {number} $index - ...
     * @param {SomeType[]} collection:SomeType - ...
     * @returns {SomeType}
     */
    rowClicked($index:number, collection:SomeType[]):number
}




Class UtilityService implements IUtilityService {

     static $inject = [
            '$http',
            '$angularCacheFactory'
        ];


        constructor(private $http : ng.IHttpService,
             private $angularCacheFactory  :ng.ICacheFactoryService) {
        }



    rowClicked($index, collection) {
        var row = collection[$index];
        if (row.current) {
            row.current = false;
            return null;
        } else {
            collection.forEach(function (object) {
                object.current = false;
            });
            row.current = true;
            return $index;
        }
    };

}


app.service('utilityService',UtilityService);

and when you consume it else where you could specify the type for your dependency as IUtilityService

Upvotes: 1

Related Questions