Here's my provider:
class testPr {
....
/** @ngInject */
$get($rootScope, $timeout, $window, FacebookService) {
const _this = this;
this.sdkInit($rootScope, $timeout, $window);
FacebookService.setPermissions(this.permissions);
const providerFunc = {
getConfig: () => {
return _this.config;
},
API_METHOD: FacebookService.API_METHOD,
PICTURE_TYPE: FacebookService.PICTURE_TYPE,
api: FacebookService.api,
checkLoginStatus: FacebookService.checkLoginStatus,
getUser: FacebookService.getUser,
getUserPicture: FacebookService.getUserPicture,
login: FacebookService.doLogin,
logout: FacebookService.doLogout,
setPermissions: FacebookService.setPermissions
};
angular.extend(providerFunc, FacebookService);
return providerFunc;
}
}
And here's my sample service:
class FacebookService {
....
checkLoginStatus(forcelogin) {
const _this = this;
const deferred = this.$q.defer();
forcelogin = (angular.isUndefined(forcelogin) || forcelogin === null) ? true : forcelogin;
this.$window.FB.getLoginStatus(response => {
if (response.status === 'connected') {
_this.currentUserAuthResponse = response.authResponse;
deferred.resolve(_this.currentUserAuthResponse);
} else if (forcelogin) {
deferred.promise = _this.doLogin();
} else {
deferred.reject({response: null, reason: 'Not logged in'});
}
});
return deferred.promise;
}
doLogin() {
const _this = this;
const deferred = this.$q.defer();
this.$window.FB.login(
response => {
if (response.authResponse) {
_this.currentUserAuthResponse = response.authResponse;
deferred.resolve(_this.currentUserAuthResponse);
} else {
deferred.reject('Not authorized!');
}
},
{
scope: _this.settings.permissions
}
);
return deferred.promise;
}
....
}
Now, when I use the provider in my controller, everything works fine, but when _this.doLogin()
is called from inside the service in checkLoginStatus
function above, I get error that doLogin is undefined. However, if I use _this.login()
, it works, since this function is returned through provider. How can I make the service functions access each other directly?
Edit: I know how the scope of this
changes in callbacks, and how to use this in such scenarios. My question is what should I use in the case mentioned in my question, as calling service methods through provider inside controller, shifts the this
scope to that of provider's even if the service functions are called within the service itself?