Closed
Description
It's common and idiomatic in Angular 1.x apps to have code like this:
angular.module('app').factory('MyService', function(service1, service2) {
class MyService {
constructor() {
this.foo = 2;
}
bar() {
return service1(this.foo, service2);
}
}
MyService.id = Math.random();
return MyService;
});
Defining classes this way (using a factory function with dependencies injected to it as its parameters) is often the right thing to do from the point of view of Angular's approach to dependency injection because:
- In its methods, the class can use dependencies provided by the container (
service1
,service2
). - The class can have static properties (
MyService.id
) that, ideally, shouldn't be shared between different instances of the container.
However, this code can't be ported easily to TypeScript as the type MyService
isn't visible for the rest of the app. We have to define also an interface for it and remember to change the interface every time the class is changed. I wish there were a way to make such types visible globally. Can't think of a good keyword for this. Probably, public
or global
will do.
angular.module('app').factory('MyService', function(service1: Service1, service2: Service2) {
public class MyService {
foo: number;
constructor() {
this.foo = 2;
}
bar() {
return service1(this.foo, service2);
}
}
// ...