繁体   English   中英

如何捕获从另一个组件发出的组件中的事件?

[英]How can i capture an event in a component which is emitted from another component?

我想捕获从另一个组件发出的事件的组件中的事件。

我做了以下代码

myservice.ts

private _event = new EventEmitter<any>();

get event(): EventEmitter<any> {
  return this._event;
}

mycomponent_2.ts

this.myservice.event.emit(true);

mycomponent_1.ts - 在 ngOnInit() 中添加以下代码

this.myservice.event.subscribe((value) =>  {
  console.log(value);
});

未打印预期的控制台日志。 看起来该事件未在 component_2 中捕获

我该如何解决这个问题? 我是否需要将代码移动到其他一些生命周期钩子?

您应该使用ReplaySubject以便它发出先前发出的值。 EventEmitter 在它们发出后丢失任何值。

如果服务尝试在创建组件之前发出值,则除非您使用缓冲主题之一,否则该值将丢失。

private _event = new ReplaySubject<any>(1);

get event(): EventEmitter<any> {
  return this._event;
}

还有BehaviorSubject允许您定义在第一次调用next()之前发出的默认值。

使用Subject :一个 Subject 就像一个 Observable,但可以多播给许多观察者。 主题就像 EventEmitters:它们维护着许多侦听器的注册表。

   @Injectable({
    providedIn: 'root',
})
export class YourService {

    private yourVariable: Subject<any> = new Subject<any>();


    public listenYourVariable() {
        return this.yourVariable.asObservable();

    }


    public yourVariableObserver(value : type) {
        this.yourVariable.next(value);
    }

您可以在您想要使用此服务的地方导入您的组件

import{ YourService } from ...

在您要编写数据调用的组件中

this.yourService.yourVariableObserver(yourData);

而你想要读取数据的地方:

  this.yourService.listenYourVariable().subscribe(
        variable => {
          this.data = variable;
        }

)

如果要使用事件,请继续阅读。 我创建了一个 repo 并通过向事件添加 @output 来使其工作,如下所示:

export class MyServiceService {
@Output() event = new EventEmitter<any>();

constructor() {}

}

然后为了确保没有计时问题,我创建了一个按钮来在一个组件中添加侦听器,并创建另一个按钮来触发事件。 因此我认为主要的错误是缺少 @Output 装饰器。

首选之一是BehaviorSubject 在这里,一个服务可用于在 2 个组件之间共享数据。

当组件彼此不相关时,它非常有用。

例如:服务:StringService

private testString=new BehaviorSubject<string>("Test") //Default value can be passed
public stringValue=this.testString.asObservable();


  passStringChange(project:string){
    this.testString.next(project)
  }

组件 1:

str:string

clickHere(){
this.stringService.passStringChange(str)
}

组件 2:

stringObtained:string
this.stringService.stringValue.subscribe(message=>this.stringObtained=message)

暂无
暂无

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

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