【问题标题】:Share data between components with Subject使用 Subject 在组件之间共享数据
【发布时间】:2018-08-03 02:57:35
【问题描述】:

我正在尝试在 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);
      }
    );
  }
}

【问题讨论】:

  • 你在哪里调用 sendData()?
  • 我猜 ProfileComponent 和 CompareComponent 没有相同的服务实例。其他人提到使用 BehaviorSubject。如果您有多个此主题的订阅者,这将是必要的,但在您的代码示例中,情况并非如此。如果您确实有多个订阅者,它确实应该是一个 BehaviorSubject。

标签: angular rxjs observable


【解决方案1】:

在役:

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

【讨论】:

    【解决方案2】:

    使用 BehaviorSubject 会订阅最新的值

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-12
      • 2020-08-31
      • 2018-10-12
      • 2020-11-08
      相关资源
      最近更新 更多