Angular 4.3 HttpClient (Angular Access REST Web Services) II. Http Request Result Type Conversion and Error Handling

Keywords: Attribute angular github JSON

Http Get Response Type Conversion

Next comes the previous section.
1. You can see in the browser console that the responding JSON object has many properties. If you try to access the login attribute with data.login, an error will be reported.
console.log(data.login);
Because Get returns an Object type.
Angular get prototype
typescript
get(url: string, options?: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe?: 'body';
params?: HttpParams | {
[param: string]: string | string[];
};
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
}): Observable<Object>;

2. The object object object of the transformation response is a custom object:
2.1 Custom Type UserResponse:

import { Component, OnInit } from '@angular/core';

import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';
  results = '';

  constructor(private http: HttpClient){
  }
  ngOnInit(): void {
    this.http.get<UserResponse>('https://api.github.com/users/seeschweiler').subscribe(data => {
      //console.log(data);
      console.log("User Login: " + data.login);
      console.log("Bio: " + data.bio);
      console.log("Company: " + data.company);
    });
  }
}
interface UserResponse {
  login: string;
  bio: string;
  company: string;
}

error handling

1. HTTP fails due to some predictable or unpredictable conditions. So there should always be code to handle these error situations. The subscribe method of Get has two parameters, no callback function, to handle the success and failure of Get.
Prototype of subscribe method

subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;

Failure handling

this.http.get<UserResponse>('https://api.github.com/users/seeschweiler').subscribe(
      data => {
        console.log("User Login: " + data.login);
        console.log("Bio: " + data.bio);
        console.log("Company: " + data.company);
      },//Added Failure Handling
      err => {
        console.log("Error occured.")
      }
    );

2. Failure details: The error handling callback function parameter type is any, which can be converted to the HttpErrorResponse type, and more error attribute information can be obtained. HttpErrorResponse needs to be imported from @angular/common/http before it can be used.
Complete app.component.ts

import { Component, OnInit } from '@angular/core';

import { HttpClient } from '@angular/common/http';
import {HttpErrorResponse} from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';
  results = '';

  constructor(private http: HttpClient){
  }
  ngOnInit(): void {
    this.http.get<UserResponse>('https://api.github.com/users/seeschweiler').subscribe(data => {
      console.log(data);
      console.log("User Login: " + data.login);
      console.log("Bio: " + data.bio);
      console.log("Company: " + data.company);
    },
    (err: HttpErrorResponse) => {
      if (err.error instanceof Error) {
        console.log("Client-side error occured.");
      } else {
        console.log("Server-side error occured.");
      }
    }
  );
  }
}
interface UserResponse {
  login: string;
  bio: string;
  company: string;
}

Posted by simwiz on Sun, 10 Feb 2019 12:57:18 -0800