首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >具有存储元素的ngOnInit中的角调用方法(订阅)

具有存储元素的ngOnInit中的角调用方法(订阅)
EN

Stack Overflow用户
提问于 2021-12-17 13:04:29
回答 1查看 560关注 0票数 0

使用商店,我订阅了特定项的所有更改。我想输出这些变化(终端消息)在一个角组件(纳克终端)。代码完成提示我编写方法。这也可以在ngOnInit()之外工作。通过控制台的输出可以工作。控件也存在(this.terminal != null)。

H

代码语言:javascript
复制
import {AfterViewInit, Component, Input, OnInit, ViewChild,} from '@angular/core';
import { select, Store } from '@ngrx/store';
**import { NgTerminal } from 'ng-terminal';**
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
import { terminalSelector } from 'src/app/stores/terminal/terminal.selectors';

@Component({
    selector: 'simu-terminal',
    templateUrl: './terminal.component.html',
    styleUrls: ['./terminal.component.scss'],
})
export class TerminalComponent implements OnInit, AfterViewInit {
    @Input() content: TerminalComponent;
    @ViewChild('term', { static: true }) terminal: NgTerminal;

    private readonly unsubscribe$ = new Subject<void>();

    constructor(private readonly store: Store) {}

    ngOnInit(): void {
        this.store
            .pipe(select(terminalSelector), takeUntil(this.unsubscribe$))
            .subscribe((msg) => {
                console.log(msg.message);
                if (this.terminal != null) {
                    this.terminal.write(msg.message);
                }
            });
    }

   ngAfterViewInit() {
        this.terminal.keyEventInput.subscribe((e) => {
            console.log('keyboard event:' + e.domEvent.keyCode + ', ' + e.key);
            const ev = e.domEvent;
            const printable = !ev.altKey && !ev.ctrlKey && !ev.metaKey;
            if (ev.keyCode === 13) {
                this.terminal.write('\r\n$ ');
            } else if (ev.keyCode === 8) {
                if (this.terminal.underlying.buffer.active.cursorX > 2) {
                    this.terminal.write('\b \b');
                }
            } else if (printable) {
                this.terminal.write(e.key);
            }
        });
    }
}

但是在ngOnInit内部,我得到了以下信息:

代码语言:javascript
复制
core.js:6498 ERROR TypeError: Cannot read properties of undefined (reading 'write')
    at NgTerminalComponent.write (ng-terminal.js:241)
    at SafeSubscriber._next (terminal.component.ts:33)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:183)
    at SafeSubscriber.next (Subscriber.js:122)
    at Subscriber._next (Subscriber.js:72)
    at Subscriber.next (Subscriber.js:49)
    at TakeUntilSubscriber._next (Subscriber.js:72)
    at TakeUntilSubscriber.next (Subscriber.js:49)
    at DistinctUntilChangedSubscriber._next (distinctUntilChanged.js:50)
    at DistinctUntilChangedSubscriber.next (Subscriber.js:49)

我做错了什么?

EN

回答 1

Stack Overflow用户

发布于 2021-12-17 22:24:05

您只需在属性名称和下一个属性之间的句点之间插入一个?

代码语言:javascript
复制
this.terminal?.write('\b \b');
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70393634

复制
相关文章

相似问题

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