Angular 5 to 6 rxjs migration

Asked

Viewed 186 times

0

Well I’m trying to migrate a new project from Angular 5 to Angular 6, but I’m having some difficulty with the way it changed the functions of rxjs, I’m posting below how I did it in Angular 5 and it worked the way I wanted, I would like a help to for example do this same function below with Angular 6 I want to always return the status as I did because depending on the status I do one thing or another.

My Service:

  login(loginUsuario: string, senhaUsuario: string): Observable<Response> {
    return this.http.get(this.apiUrl + '/login/' + loginUsuario + '/senha/' + senhaUsuario)
      .map((res:Response) => res)
      .catch((error:any) => Observable.throw(error));
  }

My page:

  onSubmit(loginUsuario, senhaUsuario) {

    this.usuarioService.login(loginUsuario, senhaUsuario)
      .subscribe (
        data => {
          if (data.status == 200) {
            localStorage.setItem("LOGIN_USUARIO_LOGADO", loginUsuario)
            this.router.navigate(['index']);
          }
        },
        error => {
          if (error.status == 401) {
            this.toastr.error("Login", "Usuário Informado Não Foi Encontrando Em Nossa Base De Dados.");
          } else if (error.status == 404) {
              this.toastr.error("Login", "A Senha Informada Está Incorreta.");
          } else if (error.status == 500) {
            this.error = error.json();
            this.toastr.error("Login", error.message); 
          } else if (error.status == 0) {
            this.toastr.error("Login", "Sem Conexão Com O WebService"); 
          }
        }
      );
  }

Solution:

usuario.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators/';

import { Usuario } from '../vo/Usuario';
import { GlobalVariableService } from '../../global-variable';

@Injectable({
  providedIn: 'root'
})
export class UsuarioService {

  private apiUrl = this.globalVariableService.apiURL + 'usuario';

  constructor(private http: HttpClient,
              private globalVariableService : GlobalVariableService) { 

  }

  saveUsuario(usuario: Usuario): Observable<any> {

    let httpHeaders = new HttpHeaders({
      'Content-Type' : 'application/json'
    });    

    return this.http.post(this.apiUrl, usuario,
      {
        headers: httpHeaders,
        observe: 'response'
      })
      .pipe(
        map((res: Response) => res),
        catchError((error: Response) => throwError(error))
      );
  }

  updateUsuario(usuario: Usuario): Observable<Response> {

    let httpHeaders = new HttpHeaders({
      'Content-Type' : 'application/json'
    });

    return this.http.put(this.apiUrl, usuario,
      {
        headers: httpHeaders,
        observe: 'response'
      })
      .pipe(
        map((res: Response) => res),
        catchError((error: Response) => throwError(error))
      );
  }

  deleteUsuarioById(codigoUsuario: number): Observable<Response> {

    let httpHeaders = new HttpHeaders({
      'Content-Type' : 'application/json'
    });

    return this.http.delete(this.apiUrl + '/' + codigoUsuario,
      {
        headers: httpHeaders,
        observe: 'response'
      })
      .pipe(
        map((res: Response) => res),
        catchError((error: Response) => throwError(error))
      );
  }

  login(loginUsuario: string, senhaUsuario: string): Observable<Response> {

    let httpHeaders = new HttpHeaders({
      'Content-Type':  'application/json',
      'loginUsuario': loginUsuario,
      'senhaUsuario': senhaUsuario
    });

    return this.http.get(this.apiUrl + '/login/',
      {
        headers: httpHeaders,
        observe: 'response'
      })
      .pipe(
        map((res: Response) => res),
        catchError((error: Response) => throwError(error))
      );
  }

  esqueceuSenha(emailUsuario: string): Observable<Response> {

    let httpHeaders = new HttpHeaders({
      'Content-Type':  'application/json',
      'emailUsuario': emailUsuario
    });

    return this.http.get(this.apiUrl + '/esqueceuSenha/',
      {
        headers: httpHeaders,
        observe: 'response'
      })
      .pipe(
        map((res: Response) => res),
        catchError((error: Response) => throwError(error))
      );
  }
}

My call on Component:

usuario.create.Component.ts

  callSave () {

    if (this.usuarioForm.valid) {

      let usuario: Usuario = new Usuario
      usuario.nomeUsuario = this.usuarioForm.controls['nomeUsuario'].value;
      usuario.loginUsuario = this.usuarioForm.controls['loginUsuario'].value;
      usuario.senhaUsuario = this.usuarioForm.controls['senhaUsuario'].value;
      usuario.emailUsuario = this.usuarioForm.controls['emailUsuario'].value;

      this.usuarioService.saveUsuario(usuario)
        .pipe(takeUntil(this.ngUnsubscribe))
        .subscribe (
          data => {
            if (data.status == 201) {
              this.toastr.success("Usuário", "Usuário Incluído Com Sucesso.");
              this.usuarioForm.reset();
            }
          },
          error => {
            debugger;
            if (error.status == 0) {
              this.toastr.error("Usuário", "Sem Conexão Com O WebService."); 
            } else if (error.status == 409) {
              this.toastr.info("Usuário", "Já Existe Esse Usuário Cadastrado, Informe Outro."); 
            } else if (error.status == 500) {
              this.toastr.error("Usuário", error.message); 
            }
          }
        );
    }
  }

1 answer

1

Ederson, in your case catch flipped catchError, he and the map must now be an importer of rxjs/Operators. Follow the example:

this.http.get(this.apiUrl + '/login/' + loginUsuario + '/senha/' + senhaUsuario)
  .pipe(
    map((res:Response) => res),
    catchError((error:any) => Observable.throw(error))
  );

For a better understanding I made an example of how your methods would look in the angular pattern/rxjs 6. Click here on link for viewing.

Doubts I’m at your disposal.

  • Very good friend, implemented here gave of good, actually it became easier than I was imagining, I was reading the documentation and was not understanding the changes had trying to make the calls in various ways already and none was working out, as you have practically just put inside the pipe, I wanted to ask a question regarding two things that I do not know what it serves for example. no ngOnDestroy() { this.ngUnsubscribe.next(); this.ngUnsubscribe.complete(); }

  • and also for what serves also the takeUntil that you put.

  • The takeUntil was used precisely to make the unsubscribe of the login method when a value is issued by the variable ngUnsubscribe. When the component is destroyed (method ngOnDestroy), we issue the ngUnsubscribe (this.ngUnsubscribe.next()) what makes the takeUntil do the unsubscribe of the login method.

  • Please inform me if the explanation :D is clear

  • I understood friend, but one more thing is the following when gives error in the program is working well, more now when it is a return OK type 200 or 201 the date comes null, you know what can be???

  • Well I found the solution I do not know if it is the most correct way but I stay this way above had to pass this note: 'Answer' on each call in the service to see the date when some request OK, but totally solved the problem.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.