简体   繁体   English

在组件之间共享数据

[英]Share Data Between Component

I want to share data between component using service.我想使用服务在组件之间共享数据。 But It not working as expected.但它没有按预期工作。

Component零件

let myNum = 1;
sendChanges(myNum) {
    this.breadService.sendData$.next(myNum);
}

Service服务

public sendData$: Subject<any> = new Subject();
public setValue$: BehaviorSubject<any> = new BehaviorSubject(this.data);

Sibling COmponent兄弟组件

ngOnInit() {
    this.breadService.sendData$.subscribe(() => {
        this.breadService.setValue$.subscribe(data=>{
            this.id = data
            console.log(this.id);
        });
    });
}

Here sendData$ is a Subject.这里sendData$是一个主题。 Subscription callbacks to a Subject aren't executed till it emits a new value.对 Subject 的订阅回调在发出新值之前不会执行。 So the inner subscription wouldn't be executed till a new value is pushed to sendData$ after it is subscribed to.因此,在订阅后将新值推送到sendData$之前,不会执行内部订阅。 You could change the outer observable too to a BehaviorSubject to assign the value in the subscription immediately.您也可以将外部 observable 更改为BehaviorSubject以立即在订阅中分配值。

Service服务

private sendDataSource: BehaviorSubject<any> = new BehaviorSubject(null);
private setValueSource: BehaviorSubject<any> = new BehaviorSubject(this.data);

public set sendData(data) {
  this.sendDataSource.next(data);
}

public set setValue(value) {
  this.setValueSource.next(value);
}

public get sendData() {
  return this.sendDataSource.asObservable();
}

public get setValue() {
  return this.setValueSource.asObservable();
}

Also a subscription within a subscription isn't elegant.订阅中的订阅也不优雅。 Pipe the outer observable. Pipe 外部可观察对象。

Sibling Component兄弟组件

import { pipe } from 'rxjs';
import { switchMap } from 'rxjs/operators';

ngOnInit() {
  this.breadService.sendData.pipe(switchMap(() => this.breadService.setValue))
    .subscribe(data => {
      this.id = data
      console.log(this.id);
    });
}

Seems like you have redundant variable and subscription好像你有多余的变量和订阅

Component零件

let myNum = 1;
sendChanges(myNum) {
    this.breadService.data$.next(myNum);
}

Service服务

public data$: BehaviorSubject<any> = new BehaviorSubject(this.data);

Sibling component同级组件

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM