Anytime I have a $inject in my service it is failing. I cannot seem to find the error. If I comment out the inject and the param on the constructor it works fine.
thanks
module app.common {
export interface IHelloService {
sayHello(text: string): string;
sayGoodbye(text: string): string
}
export class HelloService implements IHelloService {
// lokiInst: Loki;
// idbAdapter: LokiIndexedAdapter;
// usersCollection: LokiCollection<starter.domain.User>;
static $inject = ["$scope"];
constructor(private $scope:ng.IScope) {
}
sayHello(text: string): string {
return "hello" + text;
};
sayGoodbye(text: string): string {
return "goodbye"+ text;
};
}
angular.module("app.common", []);
angular
.module("starter")
.service("helloService",
HelloService);
}
You can't import $scope from a service. See the docs on this point -- only Controllers have access to this.
Depending on what you intend to do (this code doesn't use $scope so it's hard to guess), you can import $rootScope instead, or perhaps Hello ought to be a Controller rather than a Service.
Related
Using Angular 1.6 in combination with ES6-classes i ran into the following issue:
I wrote a service with some dependencies (surprise!)
class myService {
/*#ngInject*/
constructor($q){
this.$q = $q;
this.creationDate = new Date();
}
doStuff(data){
return this.$q.when(data);
}
}
angular.module('app').service('myService', myService)
However i got a build-target in which the service needed to be a bit fancier, so i extended it and used the extended service in that case instead:
class myFancyService extends myService{
/*#ngInject*/
constructor($q, $http){
super($q);
this.$http = $http;
}
doFancyStuff(data){
console.log(this.creationDate);
return this.doStuff(data)
.then((stuff) => this.$http.post('api.myapp', stuff));
}
}
angular.module('app').service('myService', myFancyService)
This works fine so far, but has a major drawback:
By calling super(dependencies), the dependencies of my base-class can't get injected automatically from #ngInject. Thus i need to be extremely aware that anytime i change the dependencies of myService, the dependencies of myFancyService (and any other potential future child-class) need to be changed as well.
I can not use Composition instead of Inheritance because myService is not registered as angular-service and thus can't be injected as dependency.
Question:
Is there a way to inject dependencies of the baseclass automatically anyways?
If not, is there at least a way to let my unittests remind me that i need to update the dependencies of myFancyService? I couldn't find a way yet to test with karma/jasmine if the arguments (or maybe just the number of arguments) of super($q) equal the (number of) arguments of the myService-constructor.
Two things to keep in mind:
in Inheritance Pattern having interface consistency is essential, child classes can re-implement methods or properties but they cannot change how a method is invoked (arguments, etc...)
You are still registering BaseService to the dependency injection but you might don't need for that, because it looks like an abstract class for you.
This could solve your problem (run script to see what's happening)
You basically need to extend the static $inject property in each derived class and use destructuring in each child constructor:
Benefits: You don't need to know what's dependencies a parent class has.
Constrains: Always use first parameters in your child class (because rest operator must be the last)
function logger(LogService) {
LogService.log('Hello World');
}
class BaseService {
static get $inject() {
return ['$q'];
}
constructor($q) {
this.$q = $q;
}
log() {
console.log('BaseService.$q: ', typeof this.$q, this.$q.name);
}
}
class ExtendedService extends BaseService {
static get $inject() {
return ['$http'].concat(BaseService.$inject);
}
constructor($http, ...rest) {
super(...rest);
this.$http = $http;
}
log() {
super.log();
console.log('ExtendedService.$http: ', typeof this.$http, this.$http.name);
}
}
class LogService extends ExtendedService {
static get $inject() {
return ['$log', '$timeout'].concat(ExtendedService.$inject);
}
constructor($log, $timeout, ...rest) {
super(...rest);
this.$log = $log;
this.$timeout = $timeout;
}
log(what) {
super.log();
this.$timeout(() => {
this.$log.log('LogService.log', what);
}, 1000);
}
}
angular
.module('test', [])
.service('BaseService', BaseService)
.service('ExtendedService', ExtendedService)
.service('LogService', LogService)
.run(logger)
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
<section ng-app="test"></section>
I have also opened a feature request in babel-plugin-angularjs-annotate:
https://github.com/schmod/babel-plugin-angularjs-annotate/issues/28
In code above super requires arguments to be specified explicitly.
A more failproof way is to do all dependency assignments in current class:
constructor($q, $http){
super();
this.$q = $q;
this.$http = $http;
}
This can create problems if these services are used in parent constructor. It's not that easy to test arguments of parent constructor because this involves module mocks. A simple and relatively reliable way to test this is to assert:
expect(service.$q).toBe($q);
expect(service.$http).toBe($http);
This should be done in any Angular unit test, in fact, even if a class wasn't inherited.
A better way is to introduce base class that handles DI, considering that all that #ngInject does is creating $inject annotation:
class Base {
constructor(...deps) {
this.constructor.$inject.forEach((dep, i) => {
this[dep] = deps[i];
}
}
}
BaseService.$inject = [];
class myService extends Base {
/*#ngInject*/
constructor($q){
super(...arguments);
...
}
...
}
At this point it becomes obvious that #ngInject doesn't really help anymore and requires to mess with arguments. Without #ngInject, it becomes:
class myService extends Base {
static get $inject() {
return ['$q'];
}
constructor(...deps){
super(...deps);
...
}
...
}
If dependency assignments are the only things that are done in child constructor, a constructor can be efficiently omitted:
class myService extends Base {
static get $inject() {
return ['$q'];
}
...
}
It's even neater with class fields and Babel/TypeScript (no native support in browsers):
class myService extends Base {
static $inject = ['$q'];
...
}
I have a child service that I want to extend from a parent service using the extends keyword. I'm having some trouble injecting another service MyService into the child service.
export class ParentService {
constructor($http) {}
get() {
this.$http.get('/someUrl').then(res => res.data);
}
}
export class ChildService extends ParentService {
constructor($http, private MyService) {
super($http);
}
get() {
const data = super.get();
return this.MyService.cleanData(data);
}
}
For some reason MyService is coming back as undefined in the ChildService, and I can only assume something is going wrong with the DI. If I remove the extends keyword however, MyService works as expected.
Any idea what might be going on here. Any help is appreciated. Thanks in advance!
Try renaming the get() methods within the ParentService and ChildService to anything else.
get is a keyword/binding-syntax that binds an object property to a function that is called when that property is looked up. The compiler is expecting a property or function name after the get and may be getting tripped up. Even in Plunkr get is highlighted by the IDE indicating a reserved word/syntax.
get could be used like this with ES6 classes:
class Todo {
constructor(task) {
this.task = task;
}
get task() {
return this.task.toUpperCase();
}
}
The get syntax binds an object property to a function that will be
called when that property is looked up.
Try changing get to getData or whatever you need.
export class ParentService {
constructor($http) {}
getData() {
return this.$http.get('/someUrl');
}
}
export class ChildService extends ParentService {
constructor($http, private MyService) {
super($http);
}
getData() {
return super.getData()
.then(data => this.MyService.cleanData(data))
.catch(error => console.log(error));
}
}
Here is a plunker demonstrating the functionality at a very basic level including a ParentService, ChildService, and a MyService, with MyService being injected into ChildService and ChildService extending ParentService. A console.log() is being executed in this example within the constructor() of the child to show that DI is occurring properly.
Hopefully this helps!
I'm getting a TypeError: this.$resource is not a function. This is my code
export class DataAccessService
implements IDataAccessService {
static $inject = ["$resource"];
constructor(private $resource: ng.resource.IResourceService) {
}
getTravelExpenseType(): ng.resource.IResourceClass<T> {
return this.$resource('URL:id', {}, {});
}
}
common.service("dataAccessService",
[DataAccessService]);
common.service("dataAccessService",
[DataAccessService]);
The problem is that you're passing an array as your service definition. When you do that, you're supposed to list the dependencies to inject in the array first, and your constructor as the last element. Since you're not listing any dependencies to inject, nothing gets injected.
Just get rid of the array:
common.service("dataAccessService", DataAccessService);
How come I don't have scope for $scope outside of the constructor, unless I define my function using the fat arrow? Or is it possible to access $scope without defining a function using fat arrow?
namespace FooBar {
export interface MyScope extends ng.IScope {
message: string;
}
export class SandboxCtrl {
static $inject = ["$scope", "$timeout"];
private scope: MyScope;
private timeout: ITimeoutService;
constructor($scope: MyScope, $timeout: ng.ITimeoutService) {
this.scope = $scope;
this.timeout = $timeout;
timeout(this.foo, 1000); // does not work
timeout(this.bar, 1000); // works
}
public foo() {
this.scope.message = "foo bar"; // does not work
}
bar = () => {
this.scope.message = "foo bar"; // works
}
}
}
UPDATE I noticed I didn't shared the entire problem as I didn't knew it was because $timeout directive which causes the problem. Anyhow I updated my example.
Try defining $scope as a property in your controller class:
export class SandboxCtrl {
static $inject = ["$scope"];
constructor(private $scope: MyScope) {
}
}
Without going into much details the problem is solved by using bind to bind this to the function.
timeout(this.foo.bind(this), 1000);
timeout(this.foo, 1000); // does not work
This is be cause foo is an unbound function and the value of this will be driven by the caller.
Just use an arrow function 🌹
More
This is covered here https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html
Looking at the answer here: https://stackoverflow.com/a/19272093/2547709
Using the $inject syntax my controller ends up looking like this:
class MyCtrl {
public static $inject: string[] = ['$scope'];
constructor($scope){
// stuff
}
}
// register the controller
app.controller("MyCtrl", MyCtrl);
My question is- what happens if I want to pass my own custom arguments to the constructor as well as any injected variables?:
class MyCtrl {
public static $inject: string[] = ['$scope'];
constructor($scope, customArg){
// stuff
}
}
// Now how do I pass customArg in without it complaining?
app.controller("MyCtrl", MyCtrl(customArg)); // Nope
I feel like I'm missing something fundamental, using this syntax, does everything you pass in to the .controller() function have to be registered with angular and so I shouldn't be trying to pass in custom arguments at all? Or can I pass in an arbitrary value/object? And if so how?
customArg
You cannot pass in custom argument if angular is going to call the constructor. You can however register other things with Angular e.g. Services,Factories,Values(constants) that angular will pass to the controller for you.
More : https://www.youtube.com/watch?v=Yis8m3BdnEM&hd=1
Sorry for the answer I don't have enough points to comment.
I have the exact same scenario and here is my situation:
export abstract class DataService<T> {
static $inject = ['$resource'];
private svc: ng.resource.IResourceClass<ng.resource.IResource<T>>;
constructor(
protected $resource: ng.resource.IResourceService, url: string
) {
this.svc = <ng.resource.IResourceClass<ng.resource.IResource<T>>>this.$resource(url, { id: '#id' });
}
public get(id: number): ng.IPromise<T> {
return this.svc.get({ id: id }).$promise;
}
}
export class MyDataService
extends DataService<IItem> {
// big problem here!!!
constructor(
) {
super("/api/items/:id");
}
}
Looks like I would have to repeat the injection on every derived class and also pass in the super... so redundant