Share data between components Angular 6

0

I have a Navbar component that is in the root of the project, and I have on the side of this component another one that is a part. Ex:

navbar
componenet1[
    component2
    component3
    component4[
        component5
        component6
    ]

]

I need to pass a data from component 6 to navbar, but only when I enter the route of this component, does anyone have an idea how to do this to help me.

    
asked by anonymous 08.06.2018 / 21:58

1 answer

1

There are two main ways to share a state between two components that have no parent / child relationship. The first would be with behavior subject with a service injected into the two components otherwise it would be by a state manager like ngrx that follows the default redux.

Example with behavior subject:

data.service.ts

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

import { Data } from '../entities/data';

@Injectable()
export class DataService {

  private dataSource = new BehaviorSubject<SnapshotSelection>(new Data());
  data = this.dataSource.asObservable();

  constructor() { }

  updatedDataSelection(data: Data){
    this.dataSource.next(data);
  }

}

Your Component

constructor(private dataService: DataService) { }

dataService.data.subscribe(data => {
// use os dados aqui
})

dataService.updateData(newData);// para atualizar os dados

Source: link

    
11.06.2018 / 09:58