2017-02-27 4 views
0

서비스를 사용하여 서로 다른 두 구성 요소가 서로 상호 작용하도록 만들려고합니다. Observable로이 작업을하려고합니다. 아이디어는 account.component.tspopup.component.ts 팝업을 표시하기 위해 popup.service.ts을 사용한다는 것입니다. 팝업 안에는 account.component.ts 내부의 기능을 실행해야하는 버튼이 있습니다.Observables와 RxJS Angular2 구성 요소의 상호 작용

계정 관리 구성 요소

export class AccountViewComponent implements OnInit { 
    constructor(popupService: PopupService) { } 
    openCancelPopup() { 
     let popup = { 
      'title': 'Popup title!', 
      'body': 'Are you really sure you wish to cancel your subscription?' 
     }; 
     this.popupService.showPopup(popup); 
     this.popupService.modalButton.subscribe(
      success => { 
       // If OK button was pressed, continue 
       console.log(success); 
      } 
     ); 
    } 
} 

팝업 서비스의 현재 상태가 표시되는 팝업과 관찰 즉시 "해결"되는

export class PopupComponent implements OnInit { 
    showPopup: boolean = false; 
    title: string; 
    body: string; 
    constructor(private popupService: PopupService) { } 

    close() { 
     this.showPopup = false; 
    } 

    openPopup(data) { 
     this.title = data.title; 
     this.body = data.body; 
     this.showPopup = true; 
     this.popupService.popupButton = new Observable(value => { 
      value.next(true); 

// I want to "resolve" here via button press 

     }); 
    } 

    ngOnInit() { 
     this.popupService.showPopupEmitter.subscribe(data => this.openPopup(data)); 
    } 
} 

@Injectable() 
export class PopupService { 
    showPopupEmitter: EventEmitter<any> = new EventEmitter(); 
    modalButton: Observable<any>; 
    constructor() { } 

    showPopup(data: Object) { 
     this.showPopupEmitter.emit(data); 
    } 
} 

팝업 구성 요소입니다. 버튼을 눌러 "해결"하면 내 기능을 계속 수행 할 수 있습니다 account.component.ts?

답변

2

관찰자 및 관찰 가능 개체 인 Subject을 사용해 볼 수 있습니다. 주제 구독

popupSubject = new Subject<bool>(); 

은 쉽게로 :

// You can chain as many Rx operators on this as you want 
let mySubscription = this.popupSubject.asObservable(); 

그리고 버튼을 누를 때마다 그냥

popupSubject.next(true) 

입니다 통해 값을 전달합니다.