"Is there a way for me to retrieve the response header within the .then function in AngularJS

How can I retrieve the response header from a GET request?

I have a service function that returns a promise. In my Controller, I resolve the promise and in the .then function, I need to access the content type from the response header.

I attempted to use the "headers" parameter, and tried to display it with console.log(headers()), but I encountered the error "headers() is not a function" in my console.

Here is My Service :

.factory('GetResultFile',
['$http', '$q',
function ($http, $q) {

    var service = {};
    service.getResult = function(id, rid) {

        var deferred = $q.defer();

        $http
        .get('http://localhost:9999/v1/jmeter/' + id + '/results/' + rid, {cache: false})
        .then(function(data, status, headers, config) {
            if(data.status == 200) {
                console.log(data.status);
                deferred.resolve(data);
            }
            else {
                deferred.reject(data);
            }
        });
        return deferred.promise;                
    }
    return service;

}]);

And here is the controller:

$scope.getResult = function(rid) {
        console.log($scope.id);
        GetResultFile.getResult($scope.id, rid)
        .then(function(data, headers) {
            //console.log(headers.Content-type);
            console.log(headers());
            console.log(data);
            console.log("Download succeed");
            console.log(data.status);

            var file = new Blob([data.data], {type: 'text/plain;charset=utf-8'});
            FileSaver.saveAs(file, 'test.txt');

        }, function (data) {
            console.log("Download ERROR!");
            console.log(data.status);
        })
    };              

}])

Answer №1

Without more specific details, my thoughts are focused on the usual standard procedures such as:

    this.$http.get('/your/Route')
      .then(response => {
        console.log(response) // Complete information
        console.log(response.data) // Contains your data
        console.log(response.config) // Contains more specific details like the URL and more
        console.log(response.headers());// Specific header information
        console.log(response.headers(["content-type"]));// Retrieves the Content-Type of the header

});

Generally pertaining to Angular Service and Response

The response object includes these properties:

  • data{string|Object} – The response body transformed with the transform functions.

  • status{number} – HTTP status code of the response.

  • headers{function([headerName])} – Header getter function.

  • config{Object} – The configuration object that was used to generate the request.

  • statusText{string} – HTTP status text of the response.

https://docs.angularjs.org/api/ng/service/$http

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

Determining whether a PFUser is being created or updated with the AfterSave function

Struggling to differentiate between whether a PFUser is being updated or saved for the first time? I tried implementing a solution from parse.com here, but it's not working as expected. No matter what, I always end up with a false value, be it an init ...

It's incredibly frustrating when the Facebook like button is nowhere to be found

Currently, I am in the process of developing a website for a local bakery and have decided to incorporate a Facebook like button on the homepage. After visiting developers.facebook, I proceeded to copy and paste the code provided. It appears that there use ...

Ways to turn off emojis in froala editor

I successfully integrated the Froala editor and dynamically generated an ID for it based on specific requirements. Everything is working well, but I now need to disable emoticons in this editor. $('#froala'+key).froalaEditor({ imageUploadP ...

Learn to leverage JavaScript in Node-RED to dynamically display messages based on selected dropdown options

After reviewing this Node-red flow: https://i.stack.imgur.com/y4aDM.png I am struggling with the implementation in my function. There are 3 options in each dropdown, one for meat type and the other for doneness. Once I select a combination from the drop ...

Objects may unexpectedly be sorted when using JavaScript or Node.js

When I execute the following code using node app.js 'use strict'; var data = {"456":"First","789":"Second","123":"Third"}; console.log(data); I am receiving the following output: { '123': 'Third', '456': 'F ...

What is the best way to change the color of my Material Icons when I move my cursor over them?

Currently, I am integrating mui icons 5.2.0 into my React application. Although the icon appears on the page, it remains unchanged in color when I try to hover over it. Check out the snippet of code that I have implemented: import EditIcon from '@mu ...

Could data be transmitted from the server to the client without appearing in network traffic?

I'm in the process of creating a drag-and-drop text game where players have to match correct pairs. Once they've matched all the pairs, they click a button to see how many they got right and wrong. The score is recorded, the boxes reset with new ...

Tips for inserting a Vue.js variable into a window.open event

Within this snippet of code: <tr v-for="person, index in People" :key='index'> <td> <button type="button" onclick="window.open('/details/'+person.id,'_blank')"> details</butto ...

Adding an additional stroke to a Material-UI Circular Progress component involves customizing the styling properties

I am attempting to create a circular progress bar with a determinate value using Material-UI, similar to the example shown in this circular progress image. However, the following code does not display the additional circle as the background: <CircularP ...

Utilizing jQuery's .slidedown alongside Prototype's .PeriodicalUpdater: A Comprehensive Guide

I am currently working on creating an activity stream that automatically updates with the latest entries from a database table every time a new row is added. Right now, I am using Prototype's Ajax.PeriodicalUpdater to continuously check for new entri ...

Bidirectional Data Binding Using Meteor and React

When using Meteor, the getMeteorData() method is preferred over getInitialState(). But how can we achieve binding, especially with regards to a user's surname in their profile? ... getMeteorData() { return { u = Meteor.user() } }, componentRen ...

Retrieve the database value for the chosen name and then add that name to a different table

I am working on a dropdown feature that fetches categories from a database and displays the selected category price in a textfield. For example, when 'web development' is selected, the price ($12) will display in the textfield. Below is the cod ...

Using Material UI with React hooks

I'm encountering an error while trying to incorporate code from Material UI. The error message is: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. Mismatc ...

I'm struggling to understand the reasoning behind the 'undefined' error occurring in the Google Maps distance service

Currently facing a puzzling issue with an 'undefined' exception. Developing a tool to track distance traveled between two locations, leveraging Google Maps distance matrix. Upon selecting a vehicle, entering an origin and destination, and clickin ...

Struggling to map a JSON file in a NextJS project using Typescript

I'm a beginner in JS and I'm currently struggling to figure out how to display the data from a json file as HTML elements. Whenever I run my code on the development server, I encounter the error message: "props.books.map is not a function&q ...

The Challenge of Logging in with the Loopback Angular SDK

I have set up a "user" named model with the base class of "User". I'm attempting to log in a user on my Angular App using the service generated by lb-ng, but it doesn't seem to be working. When I call User.login() in my Login controller, providin ...

How can I pass a dynamic scope variable to a JavaScript function in AngularJS that is being updated within an ng-repeat loop?

In my HTML, I have an ng-repeat loop where a variable is displayed in table rows. I want the user to be able to click on a value and pass it to a JavaScript function for further action. The code snippet below showcases my earlier version which successful ...

Using innerHTML in React to remove child nodes Tutorial

I'm encountering slow performance when unmounting over 30,000 components on a page using conditional rendering triggered by a button click. This process takes around 10+ seconds and causes the page to hang. Interestingly, setting the parent container& ...

Angular2/TypeScript Coding Guidelines

I am curious about the common practices and consensus among the Angular2 community when it comes to writing reusable code in TypeScript. I have gathered some information and questions related to Angular2 that I would like to discuss. Organizing Module/A ...

ngmin failing to properly annotate dependencies across multiple files

Below is the code snippet from my app.js file - var app = angular.module("app", []); In addition, here is what I have in my controller.js file - app.service("Store", function() { this.products = { item: "apple" }; }); app.controller("AppCtrl", function ...