AngularJS视图不会在嵌套的http调用上等待promise

时间:2015-09-17 13:45:17

标签: angularjs http promise

这是服务,它使用$ q并承诺等待http.jsonp返回数据。

var app=angular.module('myModule', ['ngSanitize']);
  app.service('httpq', function ($http, $q)
  {
    return {
      get: function(url) 
      {
         var defferer = $q.defer()
         $http.jsonp(url).success(function (data){
           defferer.resolve(data)
         })
         return defferer.promise
      }
    }

  });

这是控制器,它首先拆分评论文本并使用forEach& http调用从远程服务器中查找@username的用户ID,然后添加href,如[a href ="#/ app / userid] @username [/ a]

app.controller('HelloCtrl', function($scope, httpq, $http) 
  {
     var items=[];
     var url = 'https://api.instagram.com/v1/media/1059951115357899614_375673057?access_token=242292692.1fb234f.bbbbfc4972fb4bdea524e5c382cd7e48&callback=JSON_CALLBACK';

      httpq.get(url).then(function (data) {

        angular.forEach(data.data.comments.data, function(value, key) {

          var tagslistarr = value.text.split(' ');
          var text='';

          angular.forEach(tagslistarr, function(value2, key2) {

              if(value2.indexOf('@') == 0){
                username = value2.substring(1);
                var url2='https://api.instagram.com/v1/users/search?q='+username+'&count=1&access_token=242292692.1fb234f.bbbbfc4972fb4bdea524e5c382cd7e48&callback=JSON_CALLBACK';

                httpq.get(url2).then(function (data2) {

                  var userid=data2.data[0].id;
                  console.log(username+': ' + userid);
                  value2='<a href="#/event/home/user/'+userid+'/'+username+'">'+value2+'</a>';

                })

              }

              text+=value2+' ';


          });

          console.log('text: ' + text);
          items.push(text);

        });

        $scope.messages = items;

      });

  });

但是控制器没有等待第二次http调用(url2),这里是代码:

httpq.get(url2).then(function (data2) {
  //console.log("data2:"+data2.data[0].id);
  var userid=data2.data[0].id;
  console.log(username+': ' + userid);
  value2='<a href="#/event/home/user/'+userid+'/'+username+'">'+value2+'</a>';
  //console.log('str: ' + value2);
})

Here is the running demo

非常感谢任何帮助。最诚挚的问候。

0 个答案:

没有答案