如何订阅从组件触发的事件

时间:2017-10-12 15:24:58

标签: angular events components

我需要订阅我刚刚发出的事件。

“其他东西”需要“完成1件事”,但我知道Event Emmiter不可订阅。有没有其他架构或沟通来做到这一点?

非常感谢

 export class MyClass { 
     returnMethod(){
     //Does something 1
     }
 }

export class Component
    @Output() returnMethod : EventEmitter<any> = new EventEmitter();

    operation(){
       //Does something 2
       this.returnMethod.emit();
       //Something else
    }

2 个答案:

答案 0 :(得分:0)

在服务中声明Subject类型变量,并通过调用.next()来推送数据,然后在想要捕获数据的其他类中捕获该数据。

导出类MyClass {//(有一个服务实例)      结果:新的Subject();

 constructor () {
   this.result.next('fired first result');
 }
 returnMethod(){
  //Does something 1
  this.result.next('fired returnMethod result');
 }

}

现在你可以通过订阅结果来捕捉它。

// normally this is a component if angular is in context
export class myComponent {
    // normally @output being used in component
    @Output() returnMethod : EventEmitter<any> = new EventEmitter();

    constructor(private muClass: MyClass) {  // this will inject the service

    operation(){
       //Does something 2
       this.myclass.result.subscribe((res) => {
         //Something else
       });
       // this is a output variable and can be emitted if there is a child component.
       this.returnMethod.emit();

    }

答案 1 :(得分:0)

尝试使用主题,我认为事件发射器主要用于组件子 - 父通信。

服务:

@Injectable()
export class MyService {
    private subject = new Subject<any>();

    doSomething(myParam: string) {
        this.subject.next({ myParam: myParam});
    }

    getSubscription(): Observable<any> {
        return this.subject.asObservable();
    }
}

然后你的组件:

export class SomeComponent implements OnDestroy {
    subscription: Subscription;

    constructor(private myService: MyService) {
        // subscribe to home component messages
        this.subscription = 
        this.myService.getSubscription().subscribe(param=> { this.returnMethod(param.param });
    }

   returnMethod(param){
        //do your thing
    }

    ngOnDestroy() {
        // unsubscribe to ensure no memory leaks
        this.subscription.unsubscribe();
    }
}