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;
    }
}
1
  • Post an example of an responce. Commented Dec 13, 2017 at 7:35

2 Answers 2

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 !

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.