简体   繁体   中英

Creating Common Http service in angular

I am new to Angular and I have created services for every component. The service is used to fetch data from server.

It was all working fine till my client has not told me to save the request offline and sync later on.

Now, I created a common service that will hit the server and get the data rather than existing component attached services.

I wanted to know whether this will effect any thing in the project or not.

If this approach is okay, then I will check the network connection in CommonRequestService and will save the request in DB.

Please check the code below and revert. I will be very thankful.

Older Engineer Status Service

export class engineerStatusService {
    constructor(public http: Http) {}
    // Post data to the server if user update the status
    post(path: string, body: Object = {}): Observable < any > {
        let headers = new Headers({
            'Content-Type': 'application/x-www-form-urlencoded',
            'authorization': 'Bearer ' + localStorage.getItem('token')
        });
        let options = new RequestOptions({
            headers: headers
        });
        let data = body;
        let urlSearchParams = new URLSearchParams();
        for (var key in body) {
            urlSearchParams.append(key, body[key]);
        }

        let bodyData = urlSearchParams.toString();
        return this.http.post(`${API_URL}${path}`, bodyData, options)
            .map(response => response.json());
    }
}

Updated Engineer Status Service

Here the CommonRequestService is used.

export class engineerStatusService {
    constructor(private commonRequestService: CommonRequestService) {}
    // Post data to the server if user update the status
    post(path: string, body: Object = {}): Observable < Response > {
        let data = body;
        let urlSearchParams = new URLSearchParams();
        for (var key in body) {
            urlSearchParams.append(key, body[key]);
        }
        let bodyData = urlSearchParams.toString();
        return this.commonRequestService.post(path, bodyData)
            .map(response => response.json())
    }
}

CommonRequestService

export class CommonRequestService {
    constructor(private http: Http) {}
    post(path: string, body: Object = {}): Observable < Response > {
        let headers = new Headers({
            'Content-Type': 'application/x-www-form-urlencoded',
            'authorization': 'Bearer ' + localStorage.getItem('token')
        });
        let options = new RequestOptions({
            headers: headers
        });
        return this.http.post(`${API_URL}${path}`, body, options)
    }
}

Engineer Status Component

updateStatus(data) {
    this.engineerStatusService
        .post('status', data)
        .subscribe(data => {
            console.log(JSON.stringify(data));
        }, error => {
            console.log('Error occured =>', error);
        })
}

Since you already did it, I guess you only need support, right ?

Because if you're willing to do it again, here are two leads for you :

1 - The service workers , on recent browsers, that are very powerful

2 - Http Interceptors , that catch every request you make, and do something before processing them. This is the solution I recommend to you : it's powerful, built-in, and requires a lesser amount of code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM