2. crear clase del servicio
import { Injectable } from '@angular/core';
import { HttpClient , HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import { LoadingController } from '@ionic/angular';
import { appConfig } from 'src/app/global/app.config';
const URL = appConfig.api;
@Injectable({ providedIn:'root' })
export class PushPatient {
constructor(private http: HttpClient, public loadingController: LoadingController){ }
};
3. crear funciones para optimizar
3.1 suscripcion
3.2 cabezera
3.3 menejador de errores
3.4 preload (only ionic)
3.1
private subscribe( request:any ){
return new Promise((resolve, reject )=>{
request.subscribe(res=>resolve(res), err=> reject(err));
});
};
3.2 (si solo valida token x storage , si va manejar otro tipo de cabezera modificar codigo)
private _httpOption( current_user:string ){
let token = "";
if( current_user ) token = localStorage.getItem( current_user );
return { headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': token })
};
};
3.3
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code, The response body may contain clues as to what went wrong,
console.error( `Backend returned code ${error.status}, ` + `body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError( error.error.message );
};
3.4
async loading() {
const loading = await this.loadingController.create({
duration: 3000,
message: 'Please wait...',
});
return await loading.present();
}
===================== EJEMPLO COMPLETO =====================
import { Injectable } from '@angular/core';
import { HttpClient , HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';
import { LoadingController } from '@ionic/angular';
import { appConfig } from 'src/app/global/app.config';
const URL = appConfig.api;
@Injectable({ providedIn:'root' })
export class PushPatient {
constructor(private http: HttpClient, public loadingController: LoadingController){ }
// Envia notificación push
async _sendPush(data: any) {
const api = "https://onesignal.com/api/v1/notifications";
const resp = await this._post(data, api, appConfig.REST_API_KEY );
return resp;
};
//========== CUSTOM FUNCTIONS ============//
async _post( data: any, _router:string, _options?:any ){
await this.loading();
let url = _router;
_options = this._httpOption( _options );
let req = await this.http.post( url, data, _options ).pipe( catchError(this.handleError) );
let resp = await this.subscribe( req );
return resp;
};
private subscribe( request:any ){
return new Promise((resolve, reject )=>{
request.subscribe(res=>resolve(res), err=> reject(err));
});
};
private _httpOption( key:string ){
return { headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': key })
};
};
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code, The response body may contain clues as to what went wrong,
console.error( `Backend returned code ${error.status}, ` + `body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError( error.error.message );
};
async loading() {
const loading = await this.loadingController.create({
duration: 3000,
message: 'Please wait...',
});
return await loading.present();
};
};
No hay comentarios.:
Publicar un comentario