Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for call REST services and global error catching with angular2 [closed]

What is the best practice to call with angular2 REST SERVICE and catch any global exceptions to handle errors and show custom messages.

Has anyone experiences with that?

like image 648
Michael Burger Avatar asked Jun 10 '16 08:06

Michael Burger


1 Answers

The best practice i have found so far is to firstly create global service and create your method related to http there. i.e for Get, Put,Post ,Delete request etc. than via using these methods call your API service request and catch there errors using catch block and display message as you want for example :-

Global_Service.ts

import {Injectable} from '@angular/core';
import {Http, Response, RequestOptions, Headers, Request, RequestMethod} from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/Rx';

@Injecable()
export class GlobalService {
    public headers: Headers;
    public requestoptions: RequestOptions;
    public res: Response;

    constructor(public http: Http) { }

    public PostRequest(url: string, data: any): any {

        this.headers = new Headers();
        this.headers.append("Content-type", "application/json");
        this.headers.append("Authorization", 'Bearer ' + key );

        this.requestoptions = new RequestOptions({
            method: RequestMethod.Post,
            url: url,
            headers: this.headers,
            body: JSON.stringify(data)
        })

        return this.http.request(new Request(this.requestoptions))
            .map((res: Response) => {
                    return [{ status: res.status, json: res }]
            })
            .catch((error: any) => {     //catch Errors here using catch block
                if (error.status === 500) {
                    // Display your message error here
                }
                else if (error.status === 400) {
                    // Display your message error here
                }
            });
    }

    public GetRequest(url: string, data: any): any { ... }

    public PutRequest(url: string, data: any): any { ... }

    public DeleteRequest(url: string, data: any): any { ... }
 }

better to provide this service as dependency at the time of bootstraping your app like this :-

bootstrap (APP, [GlobalService, .....])

than whereever you want to call the request call the request using these globalservice methods like this :-

demo.ts

export class Demo {
     ...
    constructor(public GlobalService: GlobalService) { }

    getMethodFunction(){
       this.GlobalService.PostRequest(url, data)
        .subscribe(res => {console.log(res),
                   err => {console.log(err)}
             });
    }

see also

  • catch is not working for http.get Angular2.

    Hope this may help you.

like image 140
Pardeep Jain Avatar answered Oct 20 '22 16:10

Pardeep Jain