For the sake of clarity, I've omitted some details.
I have implemented the User service using CoffeeScript's class system, but I am encountering issues when trying to access its own member functions.
User = (...) ->
'ngInject'
new class User
constructor: ->
@setRole()
login: (params) ->
params.grant_type = 'password'
request = {...}
$http(request).then (response) ->
$window.localStorage.token = response.data.access_token
payload = jwtHelper.decodeToken(response.data.access_token)
$rootScope.$broadcast EVENTS.AUTH.LOGIN
@setRole() # PROBLEM LINE
, (response) ->
if response.status == 400
$rootScope.$broadcast EVENTS.ERROR.BAD_REQUEST
...
Whenever I try to call @setRole()
, the browser reports that setRole() is undefined:
TypeError: Cannot read property 'setRole' of undefined
This translates to the following code:
User = [..., function(...) {
'ngInject';
return new (User = (function() {
function User() {
this.setRole();
console.log("User service loaded");
}
User.prototype.login = function(params) {
var request;
params.grant_type = 'password';
request = {...}
};
return $http(request).then(function(response) {
var payload;
$window.localStorage.token = response.data.access_token;
payload = jwtHelper.decodeToken(response.data.access_token);
$rootScope.$broadcast(EVENTS.AUTH.LOGIN);
return this.setRole(); # WRONG this, I PRESUME
}, function(response) {
if (response.status === 400) {
return $rootScope.$broadcast(EVENTS.ERROR.BAD_REQUEST);
}
});
};
...
My query is: why am I unable to invoke User.setRole() within my own service using the @
notation? Is there a workaround for this issue? I suspect it may be related to the mismatch between the this pointer and the User instance.