Http Get响应(Response)类型转换
接着上一节。
1。在浏览器控制台中可以看到响应的JSON对象有许多属性(properties)。如果试着用data.login访问login属性会报错。
console.log(data.login);
因为Get返回的是Object类型。
Angular get原型
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。转换响应的object对象为自定义对象:
2.1 自定义类型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;
}
错误处理
1。由于一些可预见或不可预见的状况,会导致 HTTP失败。因此应该总是有处理这些错误状况的代码存在。 Get的subscribe方法有两个参数 未回调函数,用于处理Get成功与失败的情况。
subscribe方法原型
subscribe(next?: (value: T) => void,error?: (error: any) => void,complete?: () => void): Subscription;
失败处理
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);
},//新增失败处理
err => {
console.log("Error occured.")
}
);
2。失败详细信息:错误处理回调函数参数类型是any,可将其转换为HttpErrorResponse类型,并可获取更多错误属性信息。 HttpErrorResponse 需要从@angular/common/http导入才能使用。
完整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;
}