Pass an object as a parameter to another component using Angular 2?

0

I am a beginner in Angular 2 and need to open a page (Component) and pass an object to it. The routes are mapped and in the calcularResultado function, I need to send the objects to the component defined in the "/ result" route

import { Component, OnInit } from '@angular/core';

import { QuestoesService } from "./questoes.service";

import { Router, NavigationExtras } from "@angular/router";

    @Component({
        selector: 'app-questoes',
        templateUrl: './questoes.component.html',
        styleUrls: ['./questoes.component.css']
    })
    export class QuestoesComponent implements OnInit {

        questoes:any = new QuestoesService().getQuestoes();

        questaoSelecionada: any;
        questaoSelecionadaIndex: number = 0;
        router:Router;

        constructor(router: Router) {
            this.router = router;
            this.questaoSelecionada = this.questoes[0];
        }

        ngOnInit() {

        }

        avancar(){
            this.questaoSelecionadaIndex++;
            this.questaoSelecionada =  this.questoes[this.questaoSelecionadaIndex];
        }

        voltar(){
            this.questaoSelecionadaIndex--;
            this.questaoSelecionada =  this.questoes[this.questaoSelecionadaIndex];
        }

        calcularResultado(questoes){
            this.router.navigateByUrl("/resultado");
        }
    }
    
asked by anonymous 07.03.2017 / 02:50

2 answers

2

You can use the directive:

routerLink="/resultado" [queryParams]="questoes"

or via code:

calcularResultado(){
    this.router.navigate(['/resultado'], 
      {queryParams: this.questoes});
}

or

calcularResultado(){
    let navigationExtras: NavigationExtras = {
      queryParams: this.questoes,
      //fragment: 'anchor',
      //preserveQueryParams: true,
      //preserveFragment: true
    };
    this.router.navigate(['/resultado'], 
      {queryParams: this.questoes});
}

link

    
07.03.2017 / 23:27
0

To access the parameter in the target component

  constructor(private route: ActivatedRoute) {
  }

  ngOnInit() {
    // se possivel, capture o parametro 
    let questoesParam = this.route
      .queryParamMap
      .map(params => params.get('atributo') || 'None');
  }
    
07.12.2017 / 03:42