Make HTTP Request by Post in IONIC 3

0

Someone would know how to make a request for POST, passing a value per header and two parameters, I'm doing it

data = {
'nombre_usuario' : 'josejoserra',
'password' : '1234'};

return new Promise((resolve, reject) => {
  this.http.post(this.apiUrl+'/socio/login', data,{
    headers: new HttpHeaders().set('api-key', 'apikey'),
  })
    .subscribe(res => {
      resolve(res);
    }, (err) => {
      reject(err);
    });
});
    
asked by Luis Alberto Murcia Solivella 10.12.2017 в 18:19
source

1 answer

0

First of all what we are using is Angular +2 or TypeScript, Here I give you an example of a post in Angular using Observables.

We must pay close attention to the way we send the token to the api, since there are times when the token waits along with a word like in the case of JWT where it is common to accompany it with the word "Bearer":

import {Injectable} from '@angular/core';
import {Http, Headers, Response} from '@angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

@Injectable()
export class MiProvider {

  constructor(public http: Http) {
  }

  /** metodo para guardar con observable */
  save(data): Observable<any> {
    // creamos las cabeceras
    let headers = new Headers();
    // establecemos el token de autenticacion
    headers.append('Authorization', 'Bearer ' + JSON.parse(localStorage.getItem('userData')).auth_token);
    // establecemos el contenido de la peticion
    headers.append('Content-Type', 'application/json');
    // peticion de tipo POST (Host destino, ruta, pasamos json con datos del post, cabeceras)
    return this.http.post(this.constants.getHost() + "/socio/login", JSON.stringify(data), {headers})
      // aqui estraemos lod datos para procesarlos despues con angular
      .map(this.extractData)
      // en caso de algun problema aqui se extrael el mensaje
      .catch((e) => {
        return Observable.throw(e.json().status || e.json().errors || 'Server error');
    });
  }

  /** procesamos la respuesta del api
   * @param {Response} response data from http request.
   */
  private extractData(res: Response) {
    let body = res.json();
    return body || {};
  }
}

I hope it will help you to solve your problem, greetings.

    
answered by 11.12.2017 / 19:23
source