将角度工厂中的参数用于自定义标头

Use parameters in angular factory for custom header

本文关键字:用于 自定义 参数 工厂      更新时间:2024-03-06

我正在试图找到一种方法来传递参数,这样我就可以在我的‘endpoint’变量中使用它,正如你在我的代码中看到的那样,我有url,在它的结尾我有"/clientes",但在我的API中,我也有"products"answers"travels",所以我正在寻找一种使用变量的解决方案,这样我可以更改url的结尾,否则,我将不得不创建另一个工厂,只为获得我的"产品"answers"旅行"。

angular.module('starter.services', [])

    .factory('ServiceClientes', ['$http', function ($http) {

        var endpoint = 'http://api.rep.com/api/clientes';
        var token = '99KI9Gj68CgCf70deM22Ka64chef2J2J0G9JkD0bDAcbFfd19MfacGf3FFm8CM1hG0eDiIk8';
        var credencial = 'rm@w.com:cd8cdx5ef753a06ee79fc75dc7cfe66c';
        var origem = 'mobile';

        var config = {
            url: endpoint,
            dataType: 'json',
            method: 'GET',
            data: '',
            headers: {
                'X-API-TOKEN': token,
                'X-API-CREDENCIAL': credencial,
                'X-API-ORIGEM': origem,
                "Content-Type": "application/json"
            }
        };

        return {
            getAll: function () {
                return $http(config);
            }
        };

    }]);

控制器:

.controller('PlaylistsCtrl', function ($scope, ServiceClientes) {
        ServiceClientes.getAll().success(function (data) {
            $scope.playlists = data.dados;
        }).error(function (error) {
            console.log(error);
        });

    })

然后使用一个参数使函数可注入:

var endpoint = 'http://api.rep.com/api/';
var config = {
    dataType: 'json',
    method: 'GET',
    data: '',
    headers: {
        'X-API-TOKEN': token,
        'X-API-CREDENCIAL': credencial,
        'X-API-ORIGEM': origem,
        "Content-Type": "application/json"
    }
};    
return {
    getAll: function (url) {
        config.url = endpoint + url;
        return $http(config);
    }
};

控制器:

ServiceClientes.getAll("clientes").success(function (data) {