Angular Migration 5 to 6 rxjs

0

I'm trying to migrate a new project from Angular 5 to 6, but I'm having some difficulty in 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 it, a help for example doing that same function below with Angular 6 I want to need it always returns 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:

user.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 in Component:

user.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); 
            }
          }
        );
    }
  }
    
asked by anonymous 10.11.2018 / 23:55

1 answer

1

Ederson, in your case catch becomes catchError , he and map should now be importing rxjs / operators . Here's 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 gave an example of how your methods would look in the angular pattern / rxjs 6. Click here on the link for viewing.

Questions are available.

    
11.11.2018 / 00:58