从控制器到服务

时间:2016-05-30 15:23:57

标签: angularjs promise angular-services

我将来自我的控制器的Twitter API的调用卸载到服务中:

angular.module('main')
  .service('Tweet', function ($log, $http, Config, $ionicLoading) {

    this.show = function () {
      $ionicLoading.show({
        template: '<ion-spinner></ion-spinner><br>Loading'
      }).then(function () {
        $log.log("The loading indicator is now displayed");
      });
    };

    this.hide = function () {
      $ionicLoading.hide().then(function () {
        $log.log("The loading indicator is now hidden");
      });
    };


    var consumerKey = encodeURIComponent(Config.TWITTER.CONSUMERKEY);
    var consumerSecret = encodeURIComponent(Config.TWITTER.CONSUMERSECRET);
    var tokenCredentials = btoa(consumerKey + ':' + consumerSecret);

    this.getToken = function () {
      this.show();

      return $http({
        method: 'POST',
        url: 'https://api.twitter.com/oauth2/token',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
          'Authorization': 'Basic ' + tokenCredentials
        },
        data: 'grant_type=client_credentials'
      })
        .then(function (result) {
          if (result.data && result.data.access_token) {
            $http.defaults.headers.common.Authorization = 'Bearer ' + result.data.access_token;
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    };

    this.getTimeline = function () {
      $log.log($http.defaults.headers.common.Authorization);
      return $http({
        method: 'GET',
        url: 'https://api.twitter.com/1.1/search/tweets.json?q=%40postbank',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
        }
      })
        .then(function (result) {
          return result.data.statuses;
        })
        .catch(function (error) {
          console.log(error);
        });
    };

    this.analyzeResult = function (input) {
      this.tweets = input;
      this.hide();
    };

    var that = this;

    this.getTweets = function () {
      this.getToken()
        .then(this.getTimeline)
        .then(function (result) {
          that.analyzeResult(result);
        });
    }

  });

我将服务注入主控制器并调用getTweets()函数:

angular.module('main')
  .controller('MainCtrl', function ($log, Tweet) {

    Tweet.getTweets();
  });

我可以看到所有的promises都是通过控制台执行的,但是this.tweets仍然是空的。如何将来自服务/承诺的数据发送到控制器?

1 个答案:

答案 0 :(得分:1)

服务构造函数中的

this是服务的上下文,而不是控制器。服务不应该在范围内运作。

在控制器中解包服务承诺:

var self = this;
Tweet.getTweets().then(function () {
  self.tweets = input;
});