2017-10-12 36 views
0

我需要订阅我刚发布的活动。如何订阅从组件发起的活动

“别的东西”需要“完成某事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 
    } 

回答

0

Declar一个Subject类型变量在你的服务,并通过调用.next()推数据,然后赶上在想赶上你的数据的另一个类。

export class MyClass {//(有一个服务实例) result:new 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(); 

    } 
+0

是的,这是一个组成部分,我错了,谢谢! – user3166722

+0

是否有效?如果它的父亲孩子,那么你也可以使用@output变量,然后以不同的方式发出并捕获它 –

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(); 
    } 
}