Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

211
Vistas
Correct way to do a PUT or POST in angular-in-memory-web-api

Have seen this but the question was unanswered. So asking this question again.

I was trying to implement a PUT. Which didn't work, I checked the requestInformationand response in responseInterceptor. It turns out that the control never reaches my responseInterceptor.

This is the http code:

put(url: string, body, options?:RequestOptionsArgs): Observable<StandardModelResponse>{
    console.log("inside put, url = ", url, " body = ", body);
    return this._http.put(url,body,this._updateRequestHeader(options)); 
}

The received log is:

enter image description here

My InMemoryDbService has a collection:

let sessionData = [
  {
    id: 1,
    loginActive: 0
  }
];

and it returns the collection like this:

return {sessionData}

I looked through the source, and yes indeed there is an implementation of post and put, but I could not find the in-memory-backend.service.ts file in my node-modules for debugging, instead a in-memory-backend.service.js is there. What is the right way to do this POST call, what am I missing here?

about 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You can "override" (I am not sure if that is what is happening) the post method by adding it in your implementation of InMemoryDbService

import { InMemoryDbService } from 'angular-in-memory-web-api';
import { getStatusText, STATUS } from 'angular-in-memory-web-api/http-status-codes';
import { ParsedRequestUrl, RequestInfo, RequestInfoUtilities, ResponseOptions } from 'angular-in-memory-web-api/interfaces';
.....

  post(reqInfo: RequestInfo) {

  }
...

You can implement it to do something like the implementation of the get method like it is done here: source

I hope that helps. It seems to work :)

about 4 years ago · Santiago Trujillo Denunciar

0

It is a pretty old question but I have not found any answer describing how to patch InMemoryDbService needing to customize or fix a handler of a PUT or POST operation. As I have recently faced a similar situation, I have decided to post my solution here so that somebody might find it useful.

As has already been mentioned above, post and put functions can be overridden. For instance, the code below inserts a new item in the post method and updates an existing item in the put method

export class InMemoryDatabase extends InMemoryDbService {
  createDb() {
    const heroes = [
      {id: 1, name: 'Superman'},
      {id: 2, name: 'Biowulf')
    ];
    return { heroes };
  }

  post(reqInfo: RequestInfo) {
    var collection = reqInfo.collection;
    // process only requests as /api/object/:id
    if (!collection)
      return reqInfo.utils.createResponse$(() => {
        const options: ResponseOptions = { status: STATUS.NOT_FOUND };
        return this.finishOptions(options, reqInfo);
      });

    // insert an object to the collection
    let item = reqInfo.utils.getJsonBody(reqInfo.req)
    item["id"] = this.genId(collection);
    collection.push(item);

    // respond
    return reqInfo.utils.createResponse$(() => {
      const options: ResponseOptions =
      {
        body: item,
        status: STATUS.OK
      }
      return this.finishOptions(options, reqInfo);
    });
  }

  genId(collection: any): number {
    return collection.length > 0 ? Math.max(...collection.map(hero => hero.id)) + 1 : 11;
  }

  put(reqInfo: RequestInfo) {
    var collection = reqInfo.collection;

    // process only requests as /api/object/:id
    if (!collection || !reqInfo.id)
      return reqInfo.utils.createResponse$(() => {
        const options: ResponseOptions = { status: STATUS.NOT_FOUND };
        return this.finishOptions(options, reqInfo);
      });

    // update an object
    let item = reqInfo.utils.findById(collection, reqInfo.id);
    const body = reqInfo.utils.getJsonBody(reqInfo.req)
    Object.assign(item, body);

    // respond
    return reqInfo.utils.createResponse$(() => {
      const options: ResponseOptions =
      {
        body: item,
        status: STATUS.OK
      }
      return this.finishOptions(options, reqInfo);
    });
  }

  private finishOptions(options: ResponseOptions, { headers, url }: RequestInfo) {
    options.statusText = getStatusText(options.status);
    options.headers = headers;
    options.url = URL;
    return options;
  }
}
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda