[英]Angular2 Create map subscribe
我想要一個Angular2自定義事件。 如何調用訂閱事件?
BoardComponent.ts
onClickDelete() {
this.popupService.yesno("...?").subscribe(
yes => {
console.log("E");
},
no => {
console.log("error")
}
);
}
PopupService.ts
yesno(message: string):Observable<any> {
this.subject.next({ type: 'yesno', text: message });
let obj:Observable<any> = new Observable();
//How to..? /////////////////////////////
return obj.map(() => { return {yes:'2'}; });
}
為此,您可以使用ReplaySubject。
服務內容:
import { Injectable } from '@angular/core';
import { Observable, Subject, ReplaySubject } from 'rxjs';
@Injectable()
export class EventSubscribeService {
private eventSubject: Subject<any> = new ReplaySubject(1);
constructor() { }
// set observable of this subject
get $getEventSubject(): Observable<any> {
return this.eventSubject.asObservable();
}
// remove from observer
resetEventObserver(): void {
this.eventSubject = new ReplaySubject(1);
}
// send event to observers
sendCustomEvent(param):void {
this.eventSubject.next(param); // you can send any parameter through here.
}
}
和組件:
constructor(
private serviceInstance: EventSubscribeService,
) {
//event will receive parameter.
this.serviceInstance.$getEventSubject.subscribe(event => {
// here you can do anything what you are going to do
});
}
如何制作活動?
onCustomEvent(param:any):void {
this.serviceInstance.sendCustomEvent(param);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.