Expert wanna be Expert wanna be - 1 year ago 62
AngularJS Question

AngularJS extend service using factory and get extended scope

I want to extend a service to override some method and add some method too.

But, I can not get a scope in child service. I think the parent service is not injected to child class as well, I mean it seems like just an object, not instance.

Here is my example,

Parent service,

export class ParentService implements IModalMixin {
constructor(modalMixin: IModalMixin,
private _: _.LoDashStatic) {
}

doSomething() {}

parentMethod() {
return 'Okay';
}
}


Child service,

/* @ngInject */
export function childServiceFactory(ParentService: any) {
var extended = angular.extend(ParentService, {});

// override parent method
extended.doSomething = () => {
return this.parentMethod(); // error this.parentMethod is not a function
}

return extended;
}


// and load to module

module
.service('ParentService', MyService)
.factory('ChildService', childServiceFactory)


Please advise me what I'm doing wrong?

My angular version is 1.4.3.

Answer Source

You should not use arrow function in this case, otherwise context this is not extended object.

Normal function would work:

/* @ngInject */
export function childServiceFactory(ParentService: any) {
    var extended = angular.extend(ParentService, {});

    // override parent method
    extended.doSomething = function () {
        return this.parentMethod();
    }

    return extended;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download