Accessing JSON result values in Angular's $httpIn Angular, learning how to

In my application, I am making a $http request to an API which returns an object representing a user.

$scope.profile = $http.get('api/users/' + $stateParams.userId).success(function(data) {
    console.log(data);
});

My question is, how can I assign the value of user.username from this object to $scope.profileUsername?

The data retrieved looks like this when logged in the console...

    Object
__v: 0
_id: "56a1832a36dc3d0e00c7aa3f"
aboutme: "<p>Im the Boss.</p>"
additionalProvidersData: Object
county: "waterford"
created: "2016-01-22T01:17:30.863Z"
displayName: "Chris"
firstName: "Chris"
gender: "male"
imageURL: "/modules/users/client/img/profile/saveme-placeholder.png"
profileImageURL: "../modules/users/client/img/profile/avatars/2/45.png"
provider: "local"
roles: Array[2]
updated: "2016-02-09T02:55:38.744Z"
username: "abcdef"
__proto__: Object

Answer №1

Here is a suggestion to try out:

$http.get('api/users/' + $stateParams.userId).success(function(data) {
    $scope.profileUsername = data.username;
});

It's important to note that the return values of the $http methods are promises, not the actual data itself. This is because of their asynchronous nature, and you must manipulate the data within the callback function once the HTTP request returns.

Alternatively, you can also handle it like this:

$http.get('api/users/' + $stateParams.userId).success(function(data) {
    $scope.profile = data;
});

By storing all the data in one variable, you can easily access specific properties using dot notation (profile.username) in your templates.

Answer №2

We need to

 $http.fetch('api/users/' + $stateParams.userId).then(function(response) {
            $scope.profileInfo=response.data;
        });

This data should be easily displayed in views using {{profileInfo.username}}

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

Scrolling multiple background images vertically within a div alongside text

Is there a more efficient way to create a vertical scroll like this without overcomplicating things? I feel like my approach is incorrect. https://i.sstatic.net/CRfqW.gif Currently, I have a div with a background image and the (1) / (2) / etc. positioned ...

Utilizing AJAX, a PHP script creates an HTML table that allows users to easily perform actions such as deleting, updating

I'm a beginner in the world of ajax and I am eager to utilize it with php in order to develop a table that can be edited by users directly on the webapp interface. Here's my current progress... PHP class genTable{ public function table1(){ ...

Creating dynamic VueFire references is a powerful feature that allows for more flexibility and customization

I am currently exploring the creation of refs dynamically: The initial ref I created works fine as it is hardcoded, but the second one does not seem to work because it is dynamic: firebase: function(){ return { categories: db.ref('categ ...

What is the best way to retrieve a specific <option> from a <select> element based on its

I have a <select> element that has the following structure: <select id="stdin-select" class="io-byte-box" size="10"> <option>0x5232</option> <option>0xFD13</option> <option>0x13E7</option> &l ...

React component is unable to identify prop

I'm attempting to send an array of objects from the main App.js file to a smaller component using props. However, for some reason, the prop is not being recognized within the smaller component file. https://i.stack.imgur.com/WuyFr.png https://i.stac ...

A guide to understanding decimal parsing in C#

In my C# UWP project, I am using the Newtonsoft.Json library to parse text into JSON format. The data that I am attempting to parse looks like this: [ { "id": 9, "displayNo": 1, "ygnGoldPrice": 1111111.00, "worldGoldPric ...

Buffering ceases on the video

I am experiencing an issue with 4 videos and a preloader, which should hide once all the videos are fully buffered. <div id="preload"> <h1> Download... </h1> </div> <video preload="auto" class= ...

"Looking for a way to eliminate the background of an image on NextJS? Learn

https://i.stack.imgur.com/zAsrJ.png When this image is incorporated into a Nextjs rendering, it unexpectedly includes additional content. <div className="flex flex-col items-start justify-start rounded-3xl p-4 bg-boxi w-1/3"> <div cla ...

Guide to Configuring Loader When a Component API Request is Made or State Value is Updated

Recently, I developed a react application with multiple components, each having its own store. These stores are integrated into a global store. However, I encountered an issue where I needed to display a loader on the entire screen whenever there is pendin ...

Prevent the router link from being enabled until the submit button has been clicked

On page one, there is a submit button that, when clicked, should enable a router link to navigate to page two. If the button is not clicked, the router link should remain disabled. I attempted to disable the event, but it did not work. Page Two There is ...

the async function fails to run

fetchData = async () => { try { //Accessing data from AsyncStorage let car = await AsyncStorage.getItem('CAR') this.state.DatabaseCar=[]; this.state.DatabaseCar = JSON.parse(car); alert(this.state.Da ...

Learn how to toggle the menu list visibility by clicking on a component in Vue

I seem to be having an issue with closing a menu item in vue and vuetify2. Here is the code snippet that I have: <v-menu transition="slide-y-transition" bottom left offset-y nudge-bot ...

Safari is giving me trouble with this code, even though it's working flawlessly on all

Encountering an issue with Safari 8: var link = document.createElement('a'); link.href = 'http://10.4.3.40:3000/sample_product_list'; link.download = 'sample_product_list'; document.body.appendChild(link); link.click(); Whil ...

When navigating through the paths in my Node.JS application, I encounter an issue when attempting to access a specific route from a web browser

My application is encountering an error when attempting to open the ip/delete URL. An error message stating "Cannot GET /delete" is displayed. I have been following a tutorial available at https://www.tutorialspoint.com/nodejs/nodejs_express_framework. ...

Combine JSON arrays - Previous entries

Looking to aggregate the array1 column for each cust_id after the shape_id. cust_id | shape_id | array1 | created_at | ------------------------------------------------------------- 123 | 1 | [1,2,3] | 2019-07-23 13:42:3 ...

Modifying the CSS design of specific columns within a table created using JavaScript

A unique way to showcase JSON data in a table is by utilizing a for loop within a function. This method, however, does not assign an ID or Class to the table. To hide the final three columns of this table using CSS, the following code can be employed (whe ...

One should refrain from loading the API in Angular when there is no data present, by utilizing the global.getData method

Check out this code snippet: loadNextBatch() { console.log('scrolldown'); this.pageIndex = this.pageIndex + 1; this.global.getData(`/conditions/latest?start=${this.pageIndex}&length=${this.pageSize}`) .pipe(take(1)).subscr ...

The client end encountered an issue preventing the saving of a jpeg image

I have a situation where I need to retrieve an image stored on the server and send it to the client using sockets. While I am able to display the received image on canvas, I am encountering difficulties in saving the image to the local disk. I have attempt ...

Activate the current page link in materializecss pagination

I stumbled upon a fantastic pagination plugin for Materializescss UI, available on Github, and it's working like a charm. Now, I am looking to customize this plugin by adding the ability to set the current page and have it highlighted as active. Take ...

The AJAX request is not successful because it is encountering a ReferenceError due to attempting to assign a value to an

My attempt to trigger a modal using dynamic data from the database with an AJAX function is encountering issues. Upon clicking the button to open the modal, I encounter this error: ReferenceError: assignment to undeclared variable PostRPC in category.ph ...