jxycms
10/11/2018 - 11:13 PM

http service with header

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, } from '@angular/common/http';

@Injectable()
export class HttpService {

    constructor(private http: HttpClient) { }

    getWithNoCache<T>(
        url: string
        , search?: HttpParams | {
            [param: string]: string | string[];
        }
        , next?: (value: T) => void
        , error?: (error: any) => void
        , complete?: () => void
    ) {
        const reqHeader = new HttpHeaders();
        reqHeader.set('If-Modified-Since', 'Mon, 26 Jul 1997 05:00:00 GMT');
        reqHeader.set('Cache-Control', 'no-cache');
        reqHeader.set('Pragma', 'no-cache');

        const reqOption = {
            headers: reqHeader
            , params: search
        };

        this.http.get<T>(url, reqOption)
            .subscribe(next, error, complete);
    }

    getWithCache<T>(
        url: string
        , search?: HttpParams | {
            [param: string]: string | string[];
        }
        , next?: (value: T) => void
        , error?: (error: any) => void
        , complete?: () => void
    ) {
        const reqHeader = new HttpHeaders();

        const reqOption = {
            headers: reqHeader
            , params: search
        };

        this.http.get<T>(url, reqOption)
            .subscribe(next, error, complete);
    }

    postWithJson<T>(
        url: string
        , jsonObj: Object
        , next?: (value: T) => void
        , error?: (error: any) => void
        , complete?: () => void
    ) {
        const headers = new HttpHeaders();
        headers.set('Content-Type', 'application/json');
        const options = { headers: headers };

        this.http.post<T>(url, jsonObj, options)
            .subscribe(next, error, complete);
    }

    postWithoutHeaderJson<T>(
        url: string
        , jsonObj: Object
        , next?: (value: T) => void
        , error?: (error: any) => void
        , complete?: () => void
    ) {
        const headers = new HttpHeaders();
        headers.set('Content-Type', 'json');
        const options = { headers: headers };

        this.http.post<T>(url, jsonObj, options)
            .subscribe(next, error, complete);
    }
}