AngularJS ng路由如何在解析时发出http请求

AngularJS ng-route how to make http request on resolve

本文关键字:http 请求 路由 ng AngularJS      更新时间:2023-09-26

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

默认情况下,我使用ng路由重定向到搜索模板,并从路径/search/:title重定向到结果模板,我正在尝试使用resolve在加载结果模板(plunker中的代码)之前提出请求

我面临的主要问题是,当我添加resolve时,控制器停止初始化(我想它将在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;
        })
    };

我认为您应该使用.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'
    });
  }
]);

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

我希望你得到了你想要的,在你完成了帮助他人的任务后,把你的钱还给别人。