Angular 与主题共享组件之间的数据

Angular 与主题共享组件之间的数据,angular,rxjs,observable,Angular,Rxjs,Observable,我试图在Angular 6中的两个组件之间与Subject共享数据。 不知何故,它不起作用,我也不知道为什么。我需要通过单击将数据从compare.component传递到profile.component。单击时,数据不会传递。但不知何故,当我返回,然后再次点击,它的工作。 我做错了什么 数据服务 import {Subject} from 'rxjs'; export class DataService { data = new Subject(); } profile.compon

我试图在Angular 6中的两个组件之间与Subject共享数据。 不知何故,它不起作用,我也不知道为什么。我需要通过单击将数据从compare.component传递到profile.component。单击时,数据不会传递。但不知何故,当我返回,然后再次点击,它的工作。 我做错了什么

数据服务

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']);
  }
}
export class CompareComponent implements OnInit {

  constructor(private dataService: DataService) { }

  ngOnInit() {
    this.dataService.data.subscribe(
      (data) => {
        console.log(data);
      }
    );
  }
}
比较组件

export class ProfileComponent implements OnInit {

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

  ngOnInit() {
  }

  sendData(x) {
    this.dataService.data.next(x);
    this.router.navigate(['compare']);
  }
}
export class CompareComponent implements OnInit {

  constructor(private dataService: DataService) { }

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

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

  emitdata(x: any){
    this.data.next(x);
  }
}
在比较组件中:

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

使用BehaviorSubject它将订阅最新的值

import {BehaviorSubject} from 'rxjs';

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

你在哪里打sendData?你是这样做的吗?我猜ProfileComponent和CompareComponent没有相同的服务实例。还有人提到使用行为主体。如果这个主题有多个订阅者,这将是必要的,但在代码示例中,情况并非如此。如果您确实有多个订阅者,那么它确实应该是一个行为主体。