当通过提供程序

时间:2017-05-25 08:02:12

标签: angularjs angularjs-scope angularjs-service angularjs-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;
  }
}

这是我的样品服务:

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范围转移到提供者的范围,即使在服务中调用服务函数也是如此本身吗

0 个答案:

没有答案