Advertisement
Infitek

Untitled

Jun 25th, 2021 (edited)
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. export class Employee {
  2.    id: number;
  3.    name: string;
  4.    email: string;
  5.    phone: number;
  6. }
  7.  
  8. // *************************************************  Service.ts
  9. import { Injectable } from '@angular/core';
  10. import { HttpClient, HttpHeaders } from '@angular/common/http';
  11. import { Employee } from '../shared/employee';
  12. import { Observable, throwError } from 'rxjs';
  13. import { retry, catchError } from 'rxjs/operators';
  14.  
  15. @Injectable({
  16.   providedIn: 'root'
  17. })
  18.  
  19. export class RestApiService {
  20.  
  21.   // Define API
  22.   apiURL = 'http://localhost:3000';
  23.  
  24.   constructor(private http: HttpClient) { }
  25.  
  26.   // HttpClient API get() method => Fetch employees list
  27.   getEmployees(): Observable<Employee> {
  28.     return this.http.get<Employee>('https://jsonplaceholder.typicode.com/users')
  29.     .pipe(
  30.       retry(1),
  31.       catchError(this.handleError)
  32.     )
  33.   }
  34.  
  35.   // Error handling
  36.   handleError(error) {
  37.      let errorMessage = '';
  38.      if(error.error instanceof ErrorEvent) {
  39.        // Get client-side error
  40.        errorMessage = error.error.message;
  41.      } else {
  42.        // Get server-side error
  43.        errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
  44.      }
  45.      window.alert(errorMessage);
  46.      return throwError(errorMessage);
  47.   }
  48. }
  49.  
  50. // *************************************************  Component.ts
  51. @Component({
  52.   selector: 'app-user-list',
  53.   templateUrl: './user-list.component.html',
  54.   styleUrls: ['./user-list.component.scss']
  55. })
  56. export class UserListComponent implements OnInit {
  57.   Employee: any = [];
  58.  
  59.   constructor(public restApi: RestApiService) { }
  60.  
  61.   ngOnInit(): void {
  62.     this.loadEmployees()
  63.   }
  64.  
  65.   // Get employees list
  66.   loadEmployees() {
  67.     return this.restApi.getEmployees().subscribe((data: {}) => {
  68.       this.Employee = data;
  69.     })
  70.   }
  71. }
  72.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement