[英]Angular Behavior Subject multiple arguments
我需要从一个组件中获取值并在另一个组件中获取它们,我想使用 behaviorSubject,但我不明白,如何在 behaviorSubject 中传递 2 个 arguments,我收到错误 TS2554:预期 1 个 arguments,但得到了 2 个。
//service import { Injectable } from '@angular/core'; import {BehaviorSubject} from 'rxjs'; @Injectable({ providedIn: 'root' }) interface ICellSelection { xId: number; yId: number; } export class plotService { public IdsForCellSelection: BehaviorSubject<ICellSelection> = new BehaviorSubject<ICellSelection>(null); public setIdsForCellSelection(xItemIndex: number, yItemIndex: number) { this.IdsForCellSelection.next(xItemIndex, yItemIndex); } constructor() { } }
// component public selectArea() { this.store.dispatch(({ payload: [] })); this.selectedItems = [this.xItem, this.yItem]; this.selectionChanged.emit(this.selectedItems); //here iam trying to send 2 arguments+ this.plotService.setIdsForCellSelection( this.xItemIndex, this.yItemIndex); }
BehaviourSubject 接受一个参数,而您正试图通过 2。
所以下面是不正确的:
this.IdsForCellSelection.next(xItemIndex, yItemIndex);
而是这样做:
this.IdsForCellSelection.next({xItemIndex, yItemIndex});
将其作为定义类型的 object 传递。 此外,如果不需要默认null
,则更适合将ReplaySubject
与缓冲区 1 一起使用而不是BehaviorSubject
。
服务
import { Injectable } from '@angular/core';
import { ReplaySubject } from 'rxjs';
interface ICellSelection {
xId: number;
yId: number;
}
@Injectable({ providedIn: 'root' })
export class plotService {
public IdsForCellSelection: ReplaySubject<ICellSelection> = new ReplaySubject<ICellSelection>(1);
public setIdsForCellSelection(xItemIndex: number, yItemIndex: number) {
this.IdsForCellSelection.next(
{ xId: xItemIndex, yId: yItemIndex } as ICellSelection
);
}
constructor() { }
}
要在整个应用程序中保持类型一致性,您需要在外部文件中定义类型并将其导入到需要的位置。
例如。
细胞选择.ts
export interface ICellSelection {
xId: number;
yId: number;
}
零件
import { ICellSelection } from './cell-selection';
...
public selectArea() {
this.store.dispatch(({ payload: [] }));
this.selectedItems = [this.xItem, this.yItem];
this.selectionChanged.emit(this.selectedItems);
this.plotService.setIdsForCellSelection({
xId: this.xItemIndex,
yId: this.yItemIndex
} as ICellSelection);
}
服务
import { Injectable } from '@angular/core';
import { ReplaySubject } from 'rxjs';
import { ICellSelection } from './cell-selection';
@Injectable({ providedIn: 'root' })
export class plotService {
public IdsForCellSelection: ReplaySubject<ICellSelection> = new ReplaySubject<ICellSelection>(1);
public setIdsForCellSelection(itemIndex: ICellSelection) {
this.IdsForCellSelection.next(itemIndex);
}
constructor() { }
}
您也可以作为数组传递,如下所示:
this.IdsForCellSelection.next([xItemIndex, yItemIndex, ..]);
建议在命名变量时不要使用大写字母,并使用“$”作为可观察对象和主题的前缀,这会使您的代码在未来的开发人员中更具可读性
“idsForCellSelection$”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.