快速概述
我有一个“终端”组件,应该可以在我的应用程序中多次使用。该组件还应该能够进入“只读”模式,在该模式中,您传递一个命令,希望终端启动并显示输出。我试图让这个组件能够被许多东西刷新;数据更新,其他地方,用户事件等。为了实现这一点,我目前正在使用RxJS主题作为一个@Input进入终端组件,当更新时会触发订阅的函数。这适用于第一次用户单击(请参见下面),但在此之后主题不会再次更新。我怀疑这是由于“对象”没有更新,那里的角度没有登记的变化,我的整个想法崩溃了。
我能修好这个吗?还是我需要重新设计这个“终端”组件?
代码
terminal.component.ts
export class TerminalComponent implements OnInit, OnDestroy {
constructor() {}
$destroy = new Subject();
terminalOutput = '';
// Command input (if you want the terminal to only fire one command)
@Input() command = '';
$command: BehaviorSubject<string> = new BehaviorSubject('');
// Refresh terminal input
$refresh: Subject<void> = new Subject();
@Input() set refresh(value: Subject<void>) {
this.$refresh = value;
}
// ReadOnly Input
@Input() readOnly = false;
ngOnInit(): void {
this.$refresh
.pipe(
takeUntil(this.$destroy),
tap(() => {
const lastCommand = this.$command.getValue();
if (lastCommand) {
console.log('Refreshing, last command is:', lastCommand);
}
})
)
.subscribe();
//...
}
//...
}parent.component.html
<h1>Home</h1>
<app-terminal command="ls" [refresh]="$refreshSubject"></app-terminal>
<button (click)="refreshTest()">Refresh</button>parent.component.ts
export class ParentComponent implements OnInit {
$refreshSubject: Subject<void> = new Subject();
constructor() {}
ngOnInit(): void {}
refreshTest(): void {
console.log('Refreshing');
this.$refreshSubject.next();
}
}发布于 2022-03-09 11:20:02
因此,我发现了这个问题,这是我的代码中的另一个错误,它导致RxJS点击在第一次之后不触发。
ngOnInit(): void {
this.$refresh
.pipe(
takeUntil(this.$destroy),
tap(() => {
const lastCommand = this.$command.getValue();
if (lastCommand) {
console.log('Refreshing, last command is:', lastCommand);
throw new Error("Example Error");
// ^^^^ This will cause future Subject emits to not fire as this function has failed.
}
})
)
.subscribe();
//...
}边注:我认为问题标题应该改变,以更好地适应真正的问题与我的代码,并有更好的SEO。然而,如果这是一个完全垃圾的问题,那么我认为应该删除它。
https://stackoverflow.com/questions/71392588
复制相似问题