Redirect to page after API consumption

0

I have two components in my application made with Angular 5+. A component is a form, where I populate parameters that are passed in a GET to my REST API. This form (component1) retrieves the JSON from the API, however I need to retrieve the information it redirects to a table (my 2nd component) .

I'm currently getting the data from JSON, and popular to my Table, however I do not know how to automatically redirect to the listing page AFTER my API returns.

Form (Component 1)

import { Component, OnInit } from '@angular/core';
import { Chamado } from '../../@core/data/chamado';
import { ChamadoService } from '../../@core/data/chamado.service';
import { Router } from '@angular/router';
import { NgForm } from '@angular/forms';

@Component({
  selector: 'ngx-form-busca',
  templateUrl: './form-busca.component.html',
  styleUrls: ['./form-busca.component.scss'],
})
export class FormBuscaComponent {

  private titulo: string;
  chamados: Chamado[] = [];
  constructor(private chamadoService: ChamadoService,
    private router: Router) { }

    onFormSubmit(userForm: NgForm) {
      this.chamadoService.getChamadosBusca(userForm.controls['solucaoProposta'].
      value, userForm.controls['projeto'].value).subscribe(products => this.chamados = products);
  }
}

API Return Listing (Component 2)

@Component({
  selector: 'ngx-lista-chamados',
  templateUrl: './lista-chamados.component.html',
  styleUrls: ['./lista-chamados.component.scss'],
})
export class ListaChamadosComponent implements OnInit {
  chamados: Chamado[] = [];
  showList: boolean;
  constructor(private chamadoService: ChamadoService) {
    this.showList = false;
  }
  fetchDataFromService() {
    this.showList = true;
    this.chamados = this.chamadoService.getChamadoData();
  }

  ngOnInit() {
    this.fetchDataFromService();
  }
}

Service:

import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';
import { Http, Response } from '@angular/http';
import { Chamado } from './chamado';
import { RequestOptions } from '@angular/http';
import { Headers } from '@angular/http';
import { of } from 'rxjs/observable/of';

const API_URL = environment.apiUrl;

@Injectable()
export class ChamadoService {
    chamados: Chamado[] = [];
    constructor(private httpClient: HttpClient) {

    }

public getChamadosBusca(textoBusca: string, modulo: string): Observable<Chamado[]> {
        const params = new HttpParams()
            .set('textoBusca', textoBusca)
            .set('modulo', modulo);
        // tslint:disable-next-line:no-console
        console.log(params.toString());
        return this.httpClient.get<Chamado[]>(API_URL + 'chamado/busca/', { params }).pipe(
            tap(chamados => {
                // tslint:disable-next-line:no-console
                console.log('fetched texto=${textoBusca}');
                // tslint:disable-next-line:no-console
                console.log(chamados);
                this.setChamadoData(chamados);
            }),
            catchError(this.handleError('getChamados', [])),
        );
    }
  setChamadoData(data: Chamado[]) {
        this.chamados = data;
    }
  getChamadoData() {
        return this.chamados;
     }
 @param operation 
 @param result
    private handleError<T>(operation = 'operation', result?: T) {
        return (error: any): Observable<T> => {
            console.error(error);
            return of(result as T);
        };
    }     

At the moment the user manually navigates to the Component 2 (list) page and there in the ngOnInit () event the table is loaded with the data that was returned in the Form call.

    
asked by anonymous 16.05.2018 / 22:40

1 answer

1

There are 3 ways you can solve this problem:

1) Simpler way: you could return the Observable from service to the component instead of doing the treatment directly on it:

Service.ts


myHttpRequest(){
  return this.http.get(url);
}

Component.ts


myConsumable(){
this.myService.myHttpRequest()
.subscribe(
(value) => {
...

//após completar a tabela você pode redirecionar
this.router.navigate()
}
);

2) Using BehaviorSubject (something like a messagebus)

Create a message bus service for the purpose of propagating information between components (publish / subscribe pattern)

  • Issue an event in the service
  • Subscribe to your component to identify when mapping and redirect using the router

3) Use Redux and observe the status:)

    
17.05.2018 / 15:17