Share data between components with Subject

僤鯓⒐⒋嵵緔 提交于 2019-12-11 15:15:40

问题


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);
      }
    );
  }
}

回答1:


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();
}



回答2:


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);
      }
    );
  }


来源:https://stackoverflow.com/questions/51660156/share-data-between-components-with-subject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!