Angular2创建地图订阅

时间:2017-05-02 09:02:03

标签: angular dictionary observable

我想要一个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'}; });
    }

1 个答案:

答案 0 :(得分:1)

您可以将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);
  }