Michael Kutateladze
Michael Kutateladze

Reputation: 43

Share data between components with Subject

I am trying to share data between two components in Angular 6 with Subject. Somehow it does not work and I can not find out why. I need to pass data from compare.component to profile.component with click. When I click, data is not passed. But somehow when I go back and then click again, it works. What do I do wrong?

data.service

import {Subject} from 'rxjs';

export class DataService {
  data = new Subject();
}

profile.component

export class ProfileComponent implements OnInit {

  constructor(private dataService: DataService, private router: Router) { }

  ngOnInit() {
  }

  sendData(x) {
    this.dataService.data.next(x);
    this.router.navigate(['compare']);
  }
}

compare.component

export class CompareComponent implements OnInit {

  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.dataService.data.subscribe(
      (data) => {
        console.log(data);
      }
    );
  }
}

Upvotes: 1

Views: 7967

Answers (2)

Suresh Kumar Ariya
Suresh Kumar Ariya

Reputation: 9764

In service:

export class DataService {
  private data = new Subject<any>();
  public data$ = this.data.asObservable();

  emitdata(x: any){
    this.data.next(x);
  }
}

In profile component:

sendData(x){
this.dataservice.emitdata(x);
}

In compare component:

ngOnInit() {
    this.dataService.data$.subscribe(
      (data) => {
        console.log(data);
      }
    );
  }

Upvotes: 4

Chellappan வ
Chellappan வ

Reputation: 27293

Use BehaviorSubject It will subscribe the latestvalue

import {BehaviorSubject} from 'rxjs';

export class DataService {
//You can set initial value as well if you want new BehaviorSubject('value');
  data = new BehaviorSubject();
}

Upvotes: 0

Related Questions