在GET http请求中注册错误功能

问题描述 投票:-1回答:4

我不知道如何处理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());   
  }

}
javascript angular http http-get
4个回答
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 
        }
    );

然后你可以随意处理你的错误。


0
投票

第1步:import 'rxjs/add/operator/catch';

第2步:

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()).catch(this.handleError);   
  }

 handleError(err){
  //Observable.throw(err);
 }

}

然后当你订阅时:

this._yourService.getPostData().subscribe(res=>{
    console.log(res);
},err=>{
    console.log(err);
});

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'
                )
}


            });
    }

0
投票

为此使用err callback

conponent.ts

constructor(private postsService:PostsService){}

ngOnInit(){
    this.postsService.getPostData().subscribe(res =>{
        console.log(res)
    },err =>{
        console.log(err)
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.