我不知道如何处理GET
API调用的错误情况。 请更新我的代码段以处理API调用失败的情况。
代码段
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
@Injectable()
export class PostsService {
constructor(private http:Http) {
}
getPostData(){
return this.http.get("https://jsonplaceholder.typicode.com/posts").map((res:Response) => res.json());
}
}
答案 0 :(得分:1)
this.PostsService.getPostData(params).subscribe(
data =>
{
//data that has come back from the api
},
err =>
{
// err will be any errors responces from the API
}
);
然后您可以根据需要处理错误。
答案 1 :(得分:0)
为此使用err callback
。
conponent.ts
constructor(private postsService:PostsService){}
ngOnInit(){
this.postsService.getPostData().subscribe(res =>{
console.log(res)
},err =>{
console.log(err)
});
}
答案 2 :(得分:0)
第1步: import'rxjs / add / operator / catch';
第2步:
从“ @ angular / core”导入{可注入};
从'@ angular / http'导入{Http,Response};
@Injectable()
导出类PostsService {
构造函数(私有http:Http){
}
getPostData(){
返回this.http.get(“ https://jsonplaceholder.typicode.com/posts”).map((res:Response)=> res.json())。catch(this.handleError);
}
handleError(err){
//Observable.throw(err);
}
}
然后订阅时:
this._yourService.getPostData()。subscribe(res => {
console.log(res);
},err => {
console.log(err);
});
答案 3 :(得分:0)
1 ) Make a different Service file where you can call rest APIs.
2) And make a call from your component by injection the services.
**For Example, Assume this is Service file assume ->**
getEvents(response) {
let accesstoken = localStorage.getItem('access_token');
let headers = new HttpHeaders();
headers = headers.append('Authorization', 'Bearer ' + accesstoken);
let url = this.baseUrl + 'getEventListingToAdmin?page=' + response.page + '&perPage=10';
var data = this.http.get(url, {headers: headers});
return data;
}
**And This is a Component Part -->**
first import the service file in component
import { AdminService } from '../../admin.service';
**Then Inject it in constructor**
constructor(private admin: AdminService) { }
ngOnInit () {
this.admin.getEvents(response)
.subscribe(
(data:any) => {
//USE CAN USE HERE LOADS
this.loading = false;
// CAN CHECK THE RESPONSE STATUS
if(data.statusCode==200){
this.managersData = data.data.EventData;
this.allItems = data.data.EventCount;
}
},
error => {
//USE CAN USE HERE LOADS
this.loading = false;
// CAN CHECK THE RESPONSE STATUS
if(error.error.statusCode===401)
{
// CAN ADD SWEET ALERT
Swal(
error.error.msg,
'error'
)
}
});
}