Dynamic url for $http get

丶灬走出姿态 提交于 2020-01-07 08:33:13

问题


Here is what i try to do : Json from "urldatas":

[{ "name" : "John" }]

JS file:

 var app = angular.module('app', []);
    app.service('service', function($http, $q){
        this.getDatas = function () {
            var datas = $http.get('urldatas', {cache: false});
            return $q.all({datas});
        };
    app.controller('FirstCtrl', function($scope, service, $http, $timeout) {
        var vm = this;
        vm.loadData = function () {
            var promise = service.getDatas();
            promise.then(function (data) {
                $scope.datas = data.datas.data;
                console.log($scope.datas);
            });
        };
    vm.loadPackages = function () {
            var url = "urlPackages" + datas.name;
            $http.get(url).then(function (response) {
            $scope.MyPackages = response.data;
        });
};

So i try to dynamicly change url in $http.get in getPackages, by values from getDatas, but i don't know how to do it. url in console shows "urlPackagesundefinded". Thanks for answers in advance.


回答1:


$q send multiple requests as an array, not as an object. remove the curly bracket and add a square bracket

var datas = $http.get('urldatas', {cache: false});
return $q.all([datas]);

since you reference the controllerAs remove the scope variables and reference them through vm.

also in then promises response data comes under data property

var promise = service.getDatas();
promise.then(function (response) {
   vm.datas = response.data.datas.data;
   console.log(vm.datas);
});


来源:https://stackoverflow.com/questions/43157767/dynamic-url-for-http-get

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!