Using Http services for storing and fetching user info: Angular 2

Knoldus Inc.
Knoldus - Technical Insights
2 min readAug 5, 2017
a2

Using Angular 2 Http get, post services is the most essential requirement when you are working on any Angular 2 app because anyhow you will have the scenario to store some user information from your end and you have to fetch some information from their end as well if you know what I mean.

So here in this blog, we are going to create an application in angular 2 which will use two services, one for getting the information from the .json file ( in this file we have an array of objects those represents color names) and list those color names on view with CSS color property, in another service we will hit post call where we send the user name and password to the API and if that is authenticated we get the token as response.

We are going to create two components: 1- List colors: this will be a get call for fetching all color names, 2- Log User: this will be the post call for posting username and password and we will get the token as a response, the app component will be the root component for our app that we will bootstrap.

Let’s code: create a trainingData.json file like:

[code language=”JavaScript”]
[
{
“id”: 1,
“name”:”mens”,
“color”: “black”
},
{
“id”: 2,
“name”:”girly”,
“color”: “pink”
},
{…}
]
[/code]

list-color.service.ts

[code language=”JavaScript”]
getColorsList() {
return this.http.get(‘../app/data/trainingData.json’).map(
(response) => response.json(),
(error: any) => console.log(‘we got error in data service’)
);
}
[/code]

Let’s see the component implementation of getColorList service function:

[code language=”JavaScript”]
ngOnInit() {
return this.listService.getColorsList().subscribe(
(data) => this.colorList = data
);
}
[/code]

You must be thinking about the post service for sending the user login info and get the reponseToken, let’s see it’s service first:

[code language=”JavaScript”]
logUserFun(user: User) {
let jsonHeader = new Headers({
‘Content-Type’: ‘application/json’
});
let Obj = {
email: user.email,
password: user.password
}

return this.http.post(‘https://reqres.in/api/register', Obj, {headers: jsonHeader}).map(
data => data.json(),
(error:any) => console.log(‘error’)
);
}
[/code]

and it’s component calling:

[code language=”JavaScript”]
logUserFun(value: any) {
this.logService.logUserFun(this.user).subscribe(
data => this.responseToken = data
);
}
[/code]

Check out the source code for this example: KFD

Please share your opinions, thanks :)

--

--

Knoldus Inc.
Knoldus - Technical Insights

Group of smart Engineers with a Product mindset who partner with your business to drive competitive advantage | www.knoldus.com