Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import { Observable } from 'rxjs';
import { Injectable, Inject } from '@angular/core';
import { Response } from '@angular/http';
import { HttpClient, HttpParams, HttpErrorResponse } from '@angular/common/http';
import { map, catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
import { MyConfigService } from './my-config.service';
@Injectable()
export class MyHttpService {
private baseurlStandalone = '/api/'; // URL to web API
private baseurlIntegrated = '/amir/prod/something/';
private url;
private isProd = false;
constructor (
private httpClient: HttpClient,
private config: MyConfigService) {
this.isProd = config.isProduction();
this.url = config.isProduction() ?
this.baseurlIntegrated : this.baseurlStandalone;
}
public get<E>(url: string, options?, mapper?): Observable<E> {
let encodedUrl = this.getProperUrl(url);
return this.httpClient
.get(encodedUrl)
.pipe(
map(json => {
return mapper ? mapper(json) : json;
}),
catchError((errorRes: HttpErrorResponse) => {
return throwError(errorRes.error || 'Server error');
})
);
}
public postRegular<E>(url: string, params = {}): Observable<E> {
return this.httpClient
.post<E>(this.getProperUrl(url), params)
.pipe(
catchError((errorRes: HttpErrorResponse) => {
return throwError(errorRes.error || 'Server error');
})
);
}
public post<E>(url: string, body, options = {}, mapper = null): Observable<E> {
return this.httpClient
.post(this.getProperUrl(url), body, options)
.pipe(
map(json => {
return mapper ? mapper(json) : json;
}),
catchError((errorRes: HttpErrorResponse) => {
if (errorRes.status === 500 && errorRes.error !== null && errorRes.error.code === 401) {
console.log('Unauthorized received from portal. Redirecting to signout page!');
window.location.href = '/Account/MustAuthTimeout';
return;
}
return throwError(errorRes.error || 'Server error');
})
);
}
private getProperUrl(url: string): string {
if (!url) { return url; }
const isP = this.config.isProduction();
// for texts
/// .. do something
return url;
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
private handleError (error: Response | any) {
// In a real world app, we might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return throwError(errMsg);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment