Dynamic url for $http get

2019-09-20 05:30发布

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条回答
我命由我不由天
2楼-- · 2019-09-20 06:12

$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);
});
查看更多
登录 后发表回答