Home > Software design >  Angular pass data between components with no relationship
Angular pass data between components with no relationship

Time:10-06

I'm trying to pass data between two different components with no relationship but am having some difficulties. Does anyone have any recommendation on how to do this? Example:

I've got a page with 3 buttons. passing a string value upon click to a variable called selectAgent.

~agents.html~

<div routerLink="/lineups/brimstone" (click)="selectAgent('brimstone')"> </div>

<div routerLink="/lineups/viper" (click)="selectAgent('viper')"> </div>

<div  routerLink="/lineups/sova" (click)="selectAgent('sova')"> </div>

Now, i'm trying to pass selectAgent into another component (called maps):

~maps.html~

<h5> selected agent: {{selectedAgent}} </h5>
    <div >
        <div  *ngFor="let map of maps">
            <img src={{map.url}} (click)='openMap(map.name)'/>
        </div>
    </div>

Which will also be appended into the URL on click:

~maps.component.ts~

openMap(setMap: any) {
    this.router.navigateByUrl(`/lineups/${selectedAgent}/${setMap}`);
    console.log(setMap);
  }

My goal is to pass the clicked variable into the h5 tag. Does anyone have any suggestions I can go off?

CodePudding user response:

test-service.service.ts

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

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

    constructor() { }

    agentComponentData: any = new Subject();
}

agent.component.html

<p>agents works!</p>

<div routerLink="/lineups/brimstone" (click)="selectAgent('brimstone')"> A </div>

<div routerLink="/lineups/viper" (click)="selectAgent('viper')"> B </div>

<div  routerLink="/lineups/sova" (click)="selectAgent('sova')"> C </div>

agent.component.ts

import { Component, OnInit } from '@angular/core';
import { TestServiceService } from '../test-service.service';

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

    constructor(private testService: TestServiceService) { }

    ngOnInit(): void {
    }

    selectAgent(data: any) {
        this.testService.agentComponentData.next(data);
    }

}

maps.component.html

<p>maps works!</p>
<h5> selected agent: {{selectedAgent}} </h5>

maps.component.ts

import { Component, OnInit } from '@angular/core';
import { TestServiceService } from '../test-service.service';

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

    selectedAgent: any;

    constructor(private testService: TestServiceService) { }

    ngOnInit(): void {
        this.testService.agentComponentData.subscribe((val: any) => {
            console.log(val);
            this.selectedAgent = val;
        });;
    }

}

CodePudding user response:

//Solution: 1
selectAgent(agent) {
 //save to session storage
 sessionStorage.setItem('Agent',agent);
}

//maps.ts
ngOnInit(){
 this.selectedAgent = sessionStorage.getItem('Agent');
}

//Solution: 2
selectAgent(selectedAgent) {
 //send in query param
 this.router.navigate(['/maps'], { queryParams: { agent: selectedAgent} });
}

//maps.ts
constructor(private route: ActivatedRoute) {
    this.route.queryParams.subscribe(params => {
      //get data from query string
      this.selectedAgent = params['agent'];
    });
  }

//Solution: 3
selectAgent(selectedAgent) {
 //set observable in service
 this.Service.Agent.next(selectedAgent);
}

//maps.ts
ngOnInit(){
this.Service.Agent.subscribe((agent) => {
  this.selectedAgent = agent; 
 }); 
}
  • Related