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?
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With