AngularJS NG-路线如何使解析HTTP请求 [英] AngularJS ng-route how to make http request on resolve

查看:158
本文介绍了AngularJS NG-路线如何使解析HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入和一个锚链接其中,在pressing它,将加载另一个模板一个简单的模板。我想这第二个模板来获取通过HTTP请求的信息。

我使用NG路由重定向到默认,并从路径/搜索/结果模板搜索模板:标题,我想使用的决心加载结果模板之前必须进行的请求(<一个HREF =htt​​p://plnkr.co/edit/naNTcm3e4V2Mpj04fhqE相对=nofollow>在plunker code)

我现在面临的主要问题是,当我加入控制器停止被初始化的决心(我猜返回后承诺,将负载)。这意味着变量,如搜索网址不被初始化和$ routeParams是空的,当我把它们打印控制器上的搜索功能。

我应该怎么做呢?

我也不能确定正确的语法决心。是第一个搜索范围的变量?

 解析:{
    搜索:searchController.search
}

对于那些懒得检查Plunker,这里是相关code:

路由

 的.config(['$ routeProvider',函数($ routeProvider){
    $ routeProvider。
      当('/搜索',{
        templateUrl:'模板/ search.html
      })。
      当('/搜索/:标题',{
        templateUrl:'模板/ result.html',
        控制器:'searchController',
        解析:{
            搜索:searchController.search
        }
      })。
      除此以外({
        redirectTo:'/搜索
      });
  }]);

searchController

  VAR searchController = search.controller('searchController',[$ HTTP,$范围,$位置,$ rootScope','$ routeParams'功能($ HTTP,$范围,$位置$ rootScope,$ routeParams){
    的console.log(控制器构造函数);
    this.searchURL ='http://www.myapifilms.com/imdb?title=%thetitle%&format=JSON';
    $ scope.response ='&LT;此处&GT响应;';
    this.title ='';
    this.defer = NULL;
    的console.log(PARAMS:+ JSON.stringify($ routeParams));
    }]);    sea​​rchController.search =功能searchMovie($ Q $ routeParams){
        sea​​rchController.defer = $ q.defer;        VAR搜索字符串= $ routeParams.title;
        URL = searchController.searchURL.replace('%thetitle%',搜索字符串);
        的console.log(URL:+网址);
        sea​​rchController.searchRequest(URL);
    };    sea​​rchController.searchRequest =功能(URL){
        $ http.get(URL).success(功能(数据){
            ....
            sea​​rchController.defer.resolve();
            返回searchController.defer.promise;
        })
        .error(功能(数据,状态,头,配置){
            ...
            sea​​rchController.defer.resolve();
            返回searchController.defer.promise;
        })
    };


解决方案

我觉得你应该创建.factory服务,并相应修改

  angular.module('对myApp',['离子','ngRoute','首发','wc.Directives']).RUN(函数($ ionicPlatform){
  $ ionicPlatform.ready(函数(){
    //默认隐藏附件栏(删除此显示键盘上方的附件栏
    //表单输入)
    如果(window.cordova&安培;&安培; window.cordova.plugins.Keyboard){
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(真);
    }
    如果(window.StatusBar){
      StatusBar.styleDefault();
    }
  })
}).factory(搜索,函数($ Q $ HTTP){
    返回{
        的getMessage:功能(){
            //返回$ q.when(回应);
            VAR承诺= $ HTTP({方法:GET,网址:'YOUR_URL'})成功(功能(数据,状态,头,配置){。
                 返回的数据;
             });
             返回的承诺;
        }
    };
})的.config(['$ routeProvider',
  功能($ routeProvider){
    $ routeProvider。
    当('/搜索',{
      templateUrl:search.html
    })。
    当('/搜索/:标题',{
      templateUrl:result.html',
      控制器:'searchController',
      / *解析:{
        搜索:searchController.search
      } * /
      解析:{
            搜索:功能(搜索){
                返回search.getMessage();
        }
      }
    })。
    除此以外({
      redirectTo:'/搜索
    });
  }
]);

您plunker分叉: http://plnkr.co/edit/Ry4LAl?p = preVIEW

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

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.

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)

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.

How should I do this?

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

resolve: {
    search: searchController.search 
}

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

Routing

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

解决方案

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

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

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

这篇关于AngularJS NG-路线如何使解析HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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