AngularJS ng-route 如何在解析时发出 http 请求 [英] AngularJS ng-route how to make http request on resolve

查看:26
本文介绍了AngularJS ng-route 如何在解析时发出 http 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a simple template with an input and an anchor link which, upon pressing it, will load another template. I want this second template to fetch the information via a http request.

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

I am using ng-route to redirect to the search template by default and to the results template from the path /search/:title, and I am trying to use resolve to make the request before loading the results template (code in plunker)

我面临的主要问题是,当我添加解析时,控制器停止初始化(我猜它会在返回承诺后加载).这意味着当我在控制器搜索功能上打印它们时,诸如搜索 URL 之类的变量未初始化,并且 $routeParams 为空.

The main problem I am facing is that when I add the resolve the controller stops being initialized (I guess it will load after the promise is returned). This means variables such as the search URL are not initialized and the $routeParams are empty when I print them on the controller search function.

我该怎么做?

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

I am also not sure about the correct syntax for the resolve. Is the first search a scope variable?

resolve: {
    search: searchController.search 
}

懒得查看Plunker的,这里是相关代码:

For the ones lazy to check on Plunker, here it is the relevant code:

路由

.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'
      });
  }]); 

搜索控制器

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 创建一个服务并进行相应的

I think you should create a service with .factory and edit accordingly:

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

Your plunker forked: http://plnkr.co/edit/Ry4LAl?p=preview

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

I hope you got what you wanted, share back your plunker after you are done for helping others.

这篇关于AngularJS ng-route 如何在解析时发出 http 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆