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

标签 javascript angularjs angular-promise ngroute

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

默认情况下,我使用 ng-route 重定向到搜索模板,并从路径/search/:title 重定向到结果模板,我试图在加载结果模板 (code in plunker) 之前使用 resolve 发出请求

我面临的主要问题是,当我添加解析时, Controller 停止初始化(我猜它会在返回 promise 后加载)。这意味着当我在 Controller 搜索功能上打印时,搜索 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'
      });
  }]); 

搜索 Controller

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 fork :http://plnkr.co/edit/Ry4LAl?p=preview

我希望你得到了你想要的,在你完成帮助他人后分享你的 plunker。

关于javascript - AngularJS ng-route如何在解析时发出http请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26270757/

相关文章:

javascript - 在 react 中设置传递给变量的元素的样式

javascript - 需要一些有关 D3 饼图布局的帮助,将行添加到标签

javascript - 使用向上/向下箭头通过 AngularJS 聚焦和选择列表值

javascript - AngularJS + Ionic - 如何使用延迟 promise 从第一个 Controller 调用第二个 Controller 上的方法?

javascript - Angularjs $http delete with $q promise 导致 TypeError : object is not a function

AngularJs Controller ,等待服务 $http 结果

javascript - 使用 JavaScript 读取字符串中的换行符

javascript - python Flask 动态下拉列表

javascript - 在 ng-repeat 中使用 ng-model

javascript - 强制 Angular 范围从服务更新