Fetching More Data from the API
Let's revisit the service file /src/app/data.service.ts and add the following methods: getUser(userId) {
return this.http.get('https://jsonplaceholder.typicode.com/users/'+userId)
}
getPosts() {
return this.http.get('https://jsonplaceholder.typicode.com/posts')
}
The getUser() method will provide us with a single user's information, which will accept a userId as a parameter.getPosts() will fetch some fictional posts for us to get more muscle memory with this process of communicating with services.
Visit /src/app/details/details.component.ts:
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { Observable } from 'rxjs';
import { ActivatedRoute } from "@angular/router";
@Component({
selector: 'app-details',
templateUrl: './details.component.html',
styleUrls: ['./details.component.scss']
})
export class DetailsComponent implements OnInit {
user$: Object;
constructor(private route: ActivatedRoute, private data: DataService) {
this.route.params.subscribe( params => this.user$ = params.id );
}
ngOnInit() {
this.data.getUser(this.user$).subscribe(
data => this.user$ = data
);
}
}
This, as you see, is very similar to our users component. The only difference comes when we import ActivatedRoute and call it within the constructor.The purpose of this code allows us to grab the id router parameter that we defined in the app's routing file earlier. This will give us access to the user ID and then pass it to the getUser() method that we defined.
Open up the details.component.html and specify:
<h1>{{ user$.name }}</h1>
<ul>
<li><strong>Username:</strong> {{ user$.username }}</li>
<li><strong>Email:</strong> {{ user$.email }}</li>
<li><strong>Phone:</strong> {{ user$.phone }}</li>
</ul>
Save it, and click on one of the user's names:
Fetching More Data from the API
Reviewed by Pakainfo
on
August 08, 2018
Rating:
No comments: