AngularJS ng-route如何在解析时发出http请求

时间:2014-10-09 05:09:52

标签: javascript angularjs angular-promise ngroute

我有一个带有输入和锚点链接的简单模板,按下它后,将加载另一个模板。我希望第二个模板通过http请求获取信息。

我正在使用ng-route默认重定向到搜索模板,并使用路径/ search /:title中的结果模板,我试图在加载结果模板之前使用resolve来发出请求({{ 3}})

我面临的主要问题是当我添加解析时控制器停止初始化(我猜它会在返回promise后加载)。这意味着当我在控制器搜索功能上打印变量时,搜索URL等变量未被初始化,$ routeParams为空。

我该怎么做?

我也不确定解析的正确语法。第一次搜索是范围变量吗?

resolve: {
    search: searchController.search 
}

对于懒惰检查Plunker的人,这里是相关代码:

路由

.config(['$routeProvider',function($routeProvider) {
    $routeProvider.
      when('/search', {
        templateUrl: 'templates/search.html'
      }).
      when('/search/:title', {
        templateUrl: 'templates/result.html',
        controller: 'searchController', 
        resolve: {
            search: searchController.search
        }
      }).
      otherwise({
        redirectTo: '/search'
      });
  }]); 

searchController

var searchController = search.controller('searchController', ["$http", "$scope", "$location", '$rootScope', '$routeParams', function($http, $scope, $location, $rootScope, $routeParams) {
    console.log("Controller constructor");
    this.searchURL = 'http://www.myapifilms.com/imdb?title=%thetitle%&format=JSON';
    $scope.response = '<Response here>';
    this.title = '';
    this.defer = null;
    console.log("PARAMS: " + JSON.stringify($routeParams));
    }]);

    searchController.search = function searchMovie($q, $routeParams) {
        searchController.defer = $q.defer;

        var searchString = $routeParams.title;
        url = searchController.searchURL.replace('%thetitle%', searchString);
        console.log("URL: " + url);
        searchController.searchRequest(url);
    };

    searchController.searchRequest = function(url) {
        $http.get(url).success(function(data) {
            ....
            searchController.defer.resolve(); 
            return searchController.defer.promise;
        })
        .error(function(data, status, headers, config) {
            ...
            searchController.defer.resolve(); 
            return searchController.defer.promise;
        })
    };

1 个答案:

答案 0 :(得分:2)

我认为您应该使用.factory创建一个服务并进行相应的编辑:

angular.module('myApp', ['ionic', 'ngRoute', 'starter', 'wc.Directives'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      StatusBar.styleDefault();
    }
  })
})

.factory("search", function($q, $http){
    return {
        getMessage: function(){
            //return $q.when("Response");
            var promise = $http({ method: 'GET', url: 'your_url'}).success(function(data, status, headers, config) {
                 return data;
             });
             return promise;
        }
    };
})

.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
    when('/search', {
      templateUrl: 'search.html'
    }).
    when('/search/:title', {
      templateUrl: 'result.html',
      controller: 'searchController',
      /*resolve: {
        search: searchController.search
      }*/
      resolve: {
            search: function(search){
                return search.getMessage();
        }
      }
    }).
    otherwise({
      redirectTo: '/search'
    });
  }
]);

你的掠夺者分叉:http://plnkr.co/edit/Ry4LAl?p=preview

我希望你得到你想要的东西,在你完成帮助他人之后再分享你的傻瓜。