将URL路径传递到$ http get url- AngularJS

时间:2015-12-22 00:38:17

标签: angularjs api

我试图从URL部分获取值到我的$ http getURL请求中。我尝试了一些解决方案(例如HTML5mode)但没有成功。

这是我的代码:

angular.module('myapp123.products', [])


.factory('productsApi', ['$http', '$location',
    function($http, $location){

        var BASE_URL = 'http://stashdapp-t51va1o0.cloudapp.net/api/item/';

        return {
            get: getApiData
        };

        function getData() {
            var product_id = $location.path().split("/")[3] || "Unknown"; //URL = /#/product/id/1234 <---
            return $http.get(BASE_URL + product_id);
        }
    }]
)

.controller('productsCtrl', ['$scope', '$log', 'productsApi', 'UserService',
    function($scope, $log, productsApi, UserService) {

        $scope.isVisible = function(name){
            return true;// return false to hide this artist's albums
        };

        // <======  Rewrite with accounts preferences
        productsApi.getApiData()
            .then(function (result) {
                //console.log(JSON.stringify(result.data)) //Shows log of API incoming
                $scope.products = result.data;
            })
            .catch(function (err) {
                $log.error(err);
            });
    }
]);

1 个答案:

答案 0 :(得分:0)

示例中的代码中包含很多语法错误。根据我的想法,它应该是什么样子......

angular.module('myapp123.products', [])
    .config(locationConfig)
    .factory('productsApi', productsApiFactory)
;

locationConfig.$inject = ['$locationProvider'];
function locationConfig($locationProvider) {
    $locationProvider.html5Mode(true);
}

productsApiFactory.$inject = ['$http', '$location'];
function productsApiFactory($http, $location) {
    var BASE_URL = 'http://stashdapp-t51va1o0.cloudapp.net/api/list/';

    return {
        get: getData
    };

    function getData() {
        var product_id = $location.path().split("/")[3] || "Unknown";
        return $http.get(BASE_URL + product_id);
    }
}

在此版本中,正确定义了配置功能以设置html5mode,并且每次调用$location方法时,服务工厂都配置为使用get()

您可以在这样的控制器中使用该服务:

ExampleController.$inject = ['productsApi'];
function ExampleController(productsApi) {
    productsApi.get()
        .then(function onSuccess(res) {
            // handle successful API call
        })
        .catch(function onError(err) {
            // handle failed API call
        })
    ;
}