0

这是我的提供者:

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;
  }
}

这是我的示例服务:

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;
  }
....
}

现在,当我在控制器中使用提供程序时,一切正常,但是当在上面_this.doLogin()的函数中从服务内部调用时checkLoginStatus,我得到错误,即doLogin未定义。但是,如果我使用_this.login(),它可以工作,因为此函数是通过提供程序返回的。如何使服务功能直接相互访问?

编辑:我知道this回调的变化范围,以及如何在这种情况下使用它。我的问题是在我的问题中提到的情况下我应该使用什么,因为通过控制器内部的提供者调用服务方法,this即使在服务本身中调用服务功能,也会将范围转移到提供者的范围?

4

0 回答 0