Angular 2 Jax-RS,GET快于POST

时间:2017-06-22 06:02:19

标签: java jax-rs angular2-services

我有一个使用Jax-RS的REST应用程序和使用Hibernate的Angular 2,Apache 8.5和Postgres数据库。

问题是当我保存一个新对象时,我的列表中的GET在完全POST运行之前运行。这是代码。

tabela-servicos.component.ts

import { Component, OnInit } from '@angular/core';
import { Servico } from '../servico';
import { CrudServicosService } from '../crud-servicos.service';

@Component({
  selector: 'app-tabela-servicos',
  templateUrl: './tabela-servicos.component.html',
  styleUrls: ['./tabela-servicos.component.css']
})
export class TabelaServicosComponent implements OnInit {

  titulo = "Tabela de Serviços";
  servicos: Servico[] = [];

  constructor(private servicoService: CrudServicosService) { 

  }

  ngOnInit() {
    console.log('called ngOnInit')
    this.servicoService.getServicos()
        .subscribe(s => {
          console.log(s);
            this.servicos = s;
        }, erro => console.log(erro));
  }

  remover(servico: Servico){
    this.servicoService.removerServico(servico)
    .subscribe(()  => {
      let novosServicos = this.servicos.slice(0);
      let indice = novosServicos.indexOf(servico);
      novosServicos.splice(indice, 1);
      this.servicos = novosServicos;
    });
  }
}

形状servicos.component.ts

import { Component, OnInit } from '@angular/core';
import { CrudServicosService } from '../../app/crud-servicos.service';
import { Servico } from '../../app/servico';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-form-servicos',
  templateUrl: './form-servicos.component.html',
  styleUrls: ['./form-servicos.component.css']
})
export class FormServicosComponent implements OnInit {

  titulo = "Cadastro de Servicos";
  servico: Servico;
  codigo;

  constructor(private servicoService: CrudServicosService,
              private router: Router,
              private rota:ActivatedRoute) { }

  ngOnInit() {
    this.codigo = this.rota.snapshot.params['cod'];
    if(isNaN(this.codigo)){
      this.servico = new Servico();
    } else {
      this.servico = Object.assign({},
          this.servicoService.getServicoPorCodigo(this.codigo));
    }
  }

  salvarServico(){
    if(isNaN(this.codigo)){
      this.servicoService.adicionarServico(this.servico)
    } else {
      this.servicoService.atualizaServico(this.codigo, this.servico);
    }
//    console.log("waiting 2 seconds to return page list...");
//    setTimeout(()=>{
      this.router.navigate(['/lista']);
 //   },2000);
  }

  cancelar(){
    this.router.navigate(['/lista']);
  }
}

ServicoResource.java

package resource;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.google.gson.Gson;

import dao.ServicoDAO;
import model.Servico;

@Path("servico")
public class ServicoResource {

    private static ServicoDAO servicoDao = new ServicoDAO();

    @GET
    @Path("servicos")
    @Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
    public Response test() {
        List<Servico> serv = servicoDao.getList();
        System.out.println("GET Objectos from Jax-RS");
        System.out.println("");
        return Response.ok(serv).build();
    }

    @Path("servicos/delete/{id}")
    @DELETE
    public Response removeProduto(@PathParam("id") long id){
        System.out.println("DELETE Object ID: " + id + " Jax-RS ");
        System.out.println("");
        servicoDao.remover(id);
        return Response.ok().build();
    }

    @POST//consume o objeto enviado pro back-end
    @Consumes(MediaType.APPLICATION_JSON)
    public Response adiciona(String conteudo){
        Gson gson = new Gson();
        Servico s = gson.fromJson(conteudo, Servico.class);
        servicoDao.salvar(s);
        System.out.println("POST Object Jax-RS");
        System.out.println("");
        return Response.status(200).build();
    }
}

prints from ServerLog, ConsoleBrowser and Application

当我重新加载列表页面时,在保存的对象之后,它会出现。 当我在form-servicos.component.ts类中使用下面的代码时,它可以工作,但我知道这是一个不好的做法。

 console.log ("waiting 2 seconds to return page list ...");
 setTimeout (() => {
   This.router.navigate (['/ list']);
}, 2000);

有人知道如何在保持对象之前从请求列表中解决此问题吗?

1 个答案:

答案 0 :(得分:0)

(代表OP发布)

这已经解决了。

adicionarServico(servico: Servico){
    console.log("Called persist POST "+JSON.stringify(servico));
    return this.http.post(this.baseUrl + '/servico', JSON.stringify(servico), {headers: this.headers});
  }

我改变了我的crud-service.ts以返回一个Observable&lt;回复&gt;并在:

中使用它
salvarServico(){
    this.servicoService.adicionarServico(this.servico)
      .subscribe(() => {
        console.log("Saved Success");
        this.router.navigate(['/lista']);
      });
  }