首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将空事件从父组件传递给子组件

将空事件从父组件传递给子组件
EN

Stack Overflow用户
提问于 2022-03-08 09:18:59
回答 1查看 68关注 0票数 1

快速概述

我有一个“终端”组件,应该可以在我的应用程序中多次使用。该组件还应该能够进入“只读”模式,在该模式中,您传递一个命令,希望终端启动并显示输出。我试图让这个组件能够被许多东西刷新;数据更新,其他地方,用户事件等。为了实现这一点,我目前正在使用RxJS主题作为一个@Input进入终端组件,当更新时会触发订阅的函数。这适用于第一次用户单击(请参见下面),但在此之后主题不会再次更新。我怀疑这是由于“对象”没有更新,那里的角度没有登记的变化,我的整个想法崩溃了。

我能修好这个吗?还是我需要重新设计这个“终端”组件?

代码

terminal.component.ts

代码语言:javascript
复制
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

代码语言:javascript
复制
<h1>Home</h1>

<app-terminal command="ls" [refresh]="$refreshSubject"></app-terminal>

<button (click)="refreshTest()">Refresh</button>

parent.component.ts

代码语言:javascript
复制
export class ParentComponent implements OnInit {
    $refreshSubject: Subject<void> = new Subject();

    constructor() {}

    ngOnInit(): void {}

    refreshTest(): void {
        console.log('Refreshing');
        this.$refreshSubject.next();
    }
}
EN

回答 1

Stack Overflow用户

发布于 2022-03-09 11:20:02

因此,我发现了这个问题,这是我的代码中的另一个错误,它导致RxJS点击在第一次之后不触发。

代码语言:javascript
复制
 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。然而,如果这是一个完全垃圾的问题,那么我认为应该删除它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71392588

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档