Redirect to page after API consumption

Asked

Viewed 263 times

0

I have two Components in my application made with Angular 5+. A Component is a form, where I fill in parameters that are passed in a GET to my REST API. This form (component1) retrieves the JSON from the API, but I need that after retrieving the information it redirects to the one table (my 2nd Component).

At the moment I am able to recover the data from JSON, and popular my Table, but I don’t know how to automatically redirect to the listing page after the return of my API.

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);
  }
}

List of API returns (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 then in the ngOnInit() event the table is loaded with the data that was returned in the Form call.

1 answer

1


There are 3 ways you can solve this problem:

1) Simplest way: you could return the service Observable to the Component instead of doing the treatment directly on it:

Service.ts


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

Component.


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

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

2) Using Behaviorsubject (something like a messagebus)

Creating 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 happens and redirect using the router

3) Use Redux and observe the state :)

  • thanks for the tips, it worked perfectly.

Browser other questions tagged

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