9

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

 3 years ago
source link: https://blog.knoldus.com/using-http-services-storing-fetching-user-info-angular-2/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

Reading Time: 2 minutes

a2Using 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:

xxxxxxxxxx
[
{
"id": 1,
"name":"mens",
"color": "black"
},
{
"id": 2,
"name":"girly",
"color": "pink"
},
{...}
]

list-color.service.ts

xxxxxxxxxx
getColorsList() {
return this.http.get('../app/data/trainingData.json').map(
(response) => response.json(),
(error: any) => console.log('we got error in data service')
);
}

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

xxxxxxxxxx
ngOnInit() {
return this.listService.getColorsList().subscribe(
(data) => this.colorList = data
);
}

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:

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

and it’s component calling:

xxxxxxxxxx
logUserFun(value: any) {
this.logService.logUserFun(this.user).subscribe(
data => this.responseToken = data
);
}

Check out the source code for this example: KFD

Please share your opinions, thanks 🙂



About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK