0

My Api is giving me different types of status codes for warnings and errors. I have to show different alerts based on response.

I am calling http service like this:

service.ts

@Injectable()
export class TestService {

    getData () {
        return this.http.get('publi/api/list')
            .map((response: Response) => response.json())
            .catch(this.handleError);
    }

    public handleError(error: any): Observable<any> {
        console.log(error, 'error!!!!!!');
        return Observable.throw(error.json() || 'server error');
    }
}

component.ts

export class TestComponent implements OnInit {

    constructor(private testService: TestService) { }

    ngOnInit() {
        this.getAllList();
    }

    getAllList() {
        this.testService.getData()
            .subscribe(res => this.sucessList(res),
            err => this.errList(err))
    }

    sucessList(res) {
        console.log(res, 'sucessApprovalsPermissions');
    }

    // Here I need varions
    errList(err) {
        console.log(err, 'err');
        this.errApprovalPermissions = err.message.message;
    }
}
Mel
  • 5,837
  • 10
  • 37
  • 42
Runali
  • 332
  • 1
  • 4
  • 17

2 Answers2

1

What I would do if I were you, is put up an interceptor. Interceptors are services that are called before giving you the data from your request.

For instance, here is an error interceptor :

export class ErrorHandlerService implements HttpInterceptor {

  constructor() { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next
      .handle(req)
      .catch(err => {
        /* Do what you want here */
        /* The return a thrown Observable, containing whatever you want */
        return Observable.throw(err);
      });
  }
}

You then need to provide it in a module, like so :

providers: [
  { provide: HTTP_INTERCEPTORS, useClass: ErrorHandlerService, multi: true }
]

All you need to do now, is handle the error code in the catch, and you're good to go !

0

you can use subscribe method like this

 getAllList() {
  this.testService.getData().subscribe(response => {
    if (response.status === 200 ) {
     // Write your own code here
    }
    else if (response.status === 203) {
     // your own code
    }
   }, error => {
   if (error) {
     // your own code
   }
  });
 }

this way you can get different status codes.

but if you want to catch errors too! then I would suggest you follow this: How to deal with http status codes other than 200 in Angular 2

Al Masum Fahim
  • 103
  • 2
  • 7