Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- export class Employee {
- id: number;
- name: string;
- email: string;
- phone: number;
- }
- // ************************************************* Service.ts
- import { Injectable } from '@angular/core';
- import { HttpClient, HttpHeaders } from '@angular/common/http';
- import { Employee } from '../shared/employee';
- import { Observable, throwError } from 'rxjs';
- import { retry, catchError } from 'rxjs/operators';
- @Injectable({
- providedIn: 'root'
- })
- export class RestApiService {
- // Define API
- apiURL = 'http://localhost:3000';
- constructor(private http: HttpClient) { }
- // HttpClient API get() method => Fetch employees list
- getEmployees(): Observable<Employee> {
- return this.http.get<Employee>('https://jsonplaceholder.typicode.com/users')
- .pipe(
- retry(1),
- catchError(this.handleError)
- )
- }
- // Error handling
- handleError(error) {
- let errorMessage = '';
- if(error.error instanceof ErrorEvent) {
- // Get client-side error
- errorMessage = error.error.message;
- } else {
- // Get server-side error
- errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
- }
- window.alert(errorMessage);
- return throwError(errorMessage);
- }
- }
- // ************************************************* Component.ts
- @Component({
- selector: 'app-user-list',
- templateUrl: './user-list.component.html',
- styleUrls: ['./user-list.component.scss']
- })
- export class UserListComponent implements OnInit {
- Employee: any = [];
- constructor(public restApi: RestApiService) { }
- ngOnInit(): void {
- this.loadEmployees()
- }
- // Get employees list
- loadEmployees() {
- return this.restApi.getEmployees().subscribe((data: {}) => {
- this.Employee = data;
- })
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement