Utilize Angular factory parameters for creating custom headers

Currently, I am seeking a method to pass a parameter for use in my 'endpoint' variable. As illustrated in the code snippet provided, my URL includes "/clientes" at the end. However, within my API, there are also endpoints for "products" and "travels". To avoid creating separate factories for each of these, I am exploring a solution that involves utilizing a variable to dynamically change the endpoint of the URL.

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

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

        var endpoint = 'http://api.rep.com/api/clientes';
        var token = '99KI9Gj68CgCf70deM22Ka64chef2J2J0G9JkD0bDAcbFfd19MfacGf3FFm8CM1hG0eDiIk8';
        var credencial = '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b39260b3c65282426">[email protected]</a>: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:

.controller('PlaylistsCtrl', function ($scope, ServiceClientes) {

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

Answer №1

To enhance the flexibility of your function, consider making it injectable with a parameter:

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

In the controller:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the proper way to execute this API request and retrieve the latest news data using the Fetch method?

Note: Please note that the API Key used in this code is not a real one for privacy reasons. const url = 'http://newsapi.org/v2/everything?' + 'q=platformer&' + 'apiKey=3ce15c4d1fd3485cbcf17879bab498db'; ...

Exploring Angular 6 with Universal Karma for effective module testing

Issue I have been facing challenges while testing my Angular 6 application with Karma. I am encountering errors such as: Can't bind to 'ngModel' since it isn't a known property of 'mat-select'. Although the import works in ...

Explore within another map and analyze the node to spot the differences

I have some questions about iterating through a JavaScript Object and using array functions in JavaScript. Let's assume I have the following variables: var json1 = "[{"id": 1, "name":"x"}, {"id": 2, "name":"y"}]"; var json2 = "[{"id": 1, "name":"x"}, ...

Ensure mydesign is seamlessly integrated with the asp.net page

Recently, I've been working on an Asp.net page and here's a snippet of my code: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="fisrt_page.aspx.cs" Inherits="my_project.fisrt_page" %> <!DOCTYPE html> <html xmlns="http: ...

What is preventing my textbox from accepting decimal points?

After applying this code, I encountered an issue where the textbox does not accept input with a decimal point .. <asp:TextBox ID="txtDetAmount" runat="server" AutoPostBack="true" OnTextChanged="OntxtDetAmountC ...

AngularJS: Using $watch to retrieve the index of the modified item within an array

My current situation involves an array containing multiple objects. $scope.userCompetences = []; To monitor any changes in this array, I have implemented a deep watch: $scope.$watch('userCompetences', function (newVal, oldValue) { ...

Having trouble getting the Vue.js Element-UI dialog to function properly when embedded within a child component

Take a look at the main component: <template lang="pug"> .wrapper el-button(type="primary", @click="dialogAddUser = true") New User hr // Dialog: Add User add-edit-user(:dialog-visible.sync="dialogAddUser") </template> <s ...

Tips for customizing the CSS styling of the validation ng-class error

Seeking advice: Is there a way to customize the CSS style of the 'error' validation error for ng-class in Bootstrap v3? This is my current code: ng-class="(form.datos.$invalid) && ( form.datos.$touched || submitted) ? 'error&apos ...

Having trouble parsing bytes from a protobuf message in JavaScript

In my current project, I am faced with the task of encoding and decoding bytes within a protobuf message using Javascript. It seems that working with strings is functional, but once I introduce bytes in the message definition, retrieving the data becomes a ...

How can I handle a 404 error if an object is not found in a JSON file?

Below is my code snippet where I check for the correct req.path and display specific text. However, I now need to show a 404 not found error message. I attempted placing it inside the for loop condition with break;, but it's not quite working as expe ...

Get the JSON array that corresponds to a particular country

I have been searching for a solution to my specific issue, but so far have not found one. Here is the json data I am working with: { "name": "United States", "code": "US", "label": "State", ... "province_codes": { ...

Odd behavior of jQuery Fancybox after being closed

Could someone take a look at my script below and help me figure out why my fancybox is acting so strange? I have a form that, when the fancy box closes, should clear the form data and collapse the div where the results were displayed. It seems to work corr ...

Animated text in ThreeJS

I'm interested in finding a way to animate text in ThreeJS that doesn't involve placing it directly on a plane. My ideal scenario would be to have the text appear as 2D, floating above a model. I've experimented with using divs positioned ou ...

Saving data in AngularJS

I've been thinking, is there a way to store the application values in a cache so that it only needs to load once when the main application is launched? Currently, I have a controller that sends queries to the database every time I need a user property ...

Exploring the world of three-dimensional graphics with the power of HTML5, canvas,

Here is the HTML markup I am working with: <canvas id="container" name ="container" width="300" height="300"></canvas> This is the JavaScript code: var WIDTH = 400, HEIGHT = 300; var VIEW_ANGLE = 90, ASPECT = WIDTH / HEIGHT, NEAR = 1, FAR = ...

NextJs manages the logic for processing requests both before and after they are handled

NextJs stands out from other frameworks due to its lack of support for filter chains, request pre-processing, and post-processing. Many node project developers or library creators may find these features essential for executing logic before and after API c ...

Issue with code: Only the most recent modal is being opened when multiple buttons are

Just starting out with coding and working on a web app. Trying to add two buttons at the top of the page - one for login/create an account and the other for adding reviews. Successfully implemented the first button, which displays a modal when clicked. How ...

Making changes to HTML on a webpage using jQuery's AJAX with synchronous requests

Seeking assistance to resolve an issue, I am currently stuck and have invested a significant amount of time. The situation at hand involves submitting a form using the traditional post method. However, prior to submitting the form, I am utilizing the jQue ...

JSON error: Encountered an unexpected token "o" while processing

My database table: TABLE `events` ( `event_id` INT(11) unsigned NOT NULL AUTO_INCREMENT, `event_title` VARCHAR(255) NOT NULL, `event_desc` TEXT, `event_location` VARCHAR(255) NOT NULL, `event_requirements` TEXT DEFAULT NULL, `event ...

Displaying JSON data in a browser using Node.js without the need for refreshing the page

I am currently working on a node.js server that fetches JSON data from an external source and displays it in a browser window. I need assistance in setting up an automatic update every minute to reflect any changes in the JSON without requiring a manual re ...