Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use injected services in static methods

I want to use angularjs and typescript together. I'm trying to create Orm factory with typescript and stacked with some problem.

I defined my factory class as:

class OrmModel implements IOrmModel {
    static $inject = ['$http', '$q', 'config'];

    private name:string;
    private isNewRecord:boolean = false;

    constructor(public $http:ng.IHttpService, private $q:ng.IQService, private config:Object) {
        //...
    }

    static findAll(params:ISearchParams, relations:string[]):ng.IPromise<OrmModel> {
        //...
    }
}

Here I defined factory.

OrmModule:ng.IModel = angular.module('core.orm', []);
OrmModule.factory('OrmModel', ['$http', '$q', OrmModel]);

How can I use $http or $q in findAll() method?

like image 839
Ivan Burnaev Avatar asked Apr 03 '15 13:04

Ivan Burnaev


People also ask

Can you inject into static class?

You can use dependency injection in a static class using method or property injection. However, you cannot use constructor injection in a static class because the constructor of a static class cannot accept any parameters.

What is the use of injectable in service?

The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency. Likewise, the @Injectable() decorator indicates that a component, class, pipe, or NgModule has a dependency on a service. The injector is the main mechanism.

What is difference between @inject and injectable?

We use the @Inject parameter decorator to instruct Angular we want to resolve a token and inject a dependency into a constructor. We use the @Injectable class decorators to automatically resolve and inject all the parameters of class constructor.

Can we use service without injectable?

If you want to use angular services (and Http is an angular service) you must inject them as I told above as a constructor attribute to another service / component , which means if you want to use Http you need to have your service injectable. So the answer is no, you can't do it in a nice way.


1 Answers

To live in the angular ecosystem singletons should be services. So move the findAll function into its own service. That way it can have access to other services like $http and $q.

like image 82
basarat Avatar answered Oct 05 '22 23:10

basarat