Angular 2 - accessing JSON in a array


Beginners question.
I’m working on a project which requires me to pull in information from a database and its working as you can see the data I copy/pasted on the bottom. I’m bit confused as to the format of the return data. The return data is assigned to userAuthenticated[] array but it seems like i need to run it through a for loop in order to access the data.

how can i access the data as such: {{ this.userAuthenticated.username}} instead of putting it through a for loop such as the first block of code i have below.

What am I missing?

<div *ngFor="let aut1 of this.userAuthenticated">
                    {{aut1.userID}} {{aut1.userName}} {{aut1.password}}


 return this._http
                   .get(this.authUserUrl, {search: params})
                   .map((res: Response) => res.json())


	 userAuth => this.userAuthenticated = userAuth,
	 error => this.errorMessage = <any>error);					
	console.log('from Database: ' +this.userAuthenticated);
Chrome->inspect->Network->preview displays the data as:
[{userID: "3", userName: "anna", password: "pass3"}]
	 userAuth => {this.userAuthenticated = userAuth;
                      console.log('from Database: ' +this.userAuthenticated)},
	 error => this.errorMessage = <any>error);					
	console.log('from Database: ' +this.userAuthenticated);

Going to make an assumption that you’re not understanding the fat arrow functionality in the TS. It’s basically shortcut hand of writing anonymous function.

The way I learned Angular 2 is by taking these 2 courses

Apparently, both are on sale for $10 each which is super ridiculous price for the value. I strongly recommend you take those course before you start your project.

thanks on the sales but I was hoping for a quick answer.

Based on what you’ve posted, I’d say you probably want to return the first element of the userAuth array within the subscribe callback:

userAuth => this.userAuthenticated = userAuth[0]

You’ll probably need to change the declared type of this.userAuthenticated so it’s not expecting an array to avoid errors (I’m not that familiar with TypeScript though).

Excellent. it worked, thanks fretburner,

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.