Разгрузить запрос API от контроллера к сервису

0

Я выгрузил вызов API Twitter от моего контроллера в службу:

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

Я вижу, что все обещания выполняются через консоль, но this.tweets остается пустым. Как отправить данные, поступающие из службы/обещания контроллеру?

Теги:
promise
angular-services

1 ответ

1
Лучший ответ

this в конструкторе службы - это контекст службы, а не контроллер. И службы не должны работать в сфере действия.

Обезвреживание сервиса в контроллере:

var self = this;
Tweet.getTweets().then(function () {
  self.tweets = input;
});
  • 0
    Я получаю TypeError: Cannot read property 'then' of undefined если я вставлю этот код в основной контроллер.
  • 1
    Затем вы должны вернуть обещание из getTweets , return this.getToken()...

Ещё вопросы

Сообщество Overcoder
Наверх
Меню