javascriptangularjsservicetypescript

Accessing custom service from event


I'm attempting to access a custom service from a custom event yet wheneven the event is fired the service reference is null

@Component({
selector: "my-component",
template: mySource,
legacy: { transclude: true }
})
export class myComponent {
constructor(
    @Inject("$scope") private $scope: ng.IScope,
    private myService: MyService) {

    $scope.$on('$routeChangeSuccess', function (event) {
        this.myService.myFunction();
            });
        }
    });
}

when myService is referenced the following error is shown:

Cannot read property 'myService' of null

Solution

  • The solution is not to refer to myService from within myComponent prepended with

    this.myService
    

    but instead use

    myService.myFunction()