Angular + API REST: How to confirm if a user registration was actually saved?

Discussão em 'Angular' iniciado por HadesKerbecs, Abril 2, 2025.

  1. HadesKerbecs

    HadesKerbecs Guest

    I'm developing an Angular application that registers users in a REST API. The problem is that after calling the API, I receive a 200 (OK) response with seemingly valid data, but when I list the users again, the newly registered user does not appear.

    I want to understand:

    1-If the user was actually saved in the API or if the success response was returned without persisting the data.

    2-If there is something in my Angular code preventing the new user from appearing.

    cadastrar(usuario: CadastroRequest): void {
    this.consultaAPICadastroService.cadastrarUsuario(usuario)
    .subscribe({
    next: (novoUsuario) => {
    console.log("✅ Resposta da API:", novoUsuario);
    if (novoUsuario && novoUsuario.id) {
    console.log(" Usuário cadastrado com sucesso:", novoUsuario);
    } else {
    console.warn("⚠️ Usuário pode não ter sido cadastrado corretamente!", novoUsuario);
    }
    this.listar();
    },
    error: (err) => {
    console.error("❌ Erro ao cadastrar usuário:", err);
    if (err.error) {
    console.error(" Detalhes do erro:", err.error);
    if (err.error.errors) {
    console.error(" Erros específicos:", err.error.errors);
    }
    }
    }
    });
    }


    API

    @Injectable({
    providedIn: 'root'
    })
    export class ConsultaAPICadastroService {
    apiUrl = "";

    constructor(private http: HttpClient) {}

    cadastrarUsuario(usuario: CadastroRequest): Observable<any> {
    const token = localStorage.getItem('access_token');
    if (!token) {
    console.error("Erro: Token de autenticação não encontrado.");
    throw new Error("Token não encontrado.");
    }

    const { cadastro_tipo_id, ...payload } = usuario;
    const headers = new HttpHeaders({
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json',
    'Accept': 'application/json'
    });

    console.log("Dados enviados para API:", JSON.stringify(payload));
    return this.http.post<any>(this.apiUrl, payload, { headers });
    }
    }

    Continue reading...

Compartilhe esta Página