Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

301
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda