[英]RxJS Angular2 Component interaction with Observables
我正在嘗試使用服務使2個不同的組件相互交互。 我正在嘗試使用Observable。 這個想法是account.component.ts
將使用popup.service.ts
顯示一個彈出窗口popup.component.ts
。 在彈出窗口中,有一個按鈕需要在彈出窗口中按下后在account.component.ts
內部運行一個函數。
帳戶部分
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);
}
);
}
}
彈出服務
@Injectable()
export class PopupService {
showPopupEmitter: EventEmitter<any> = new EventEmitter();
modalButton: Observable<any>;
constructor() { }
showPopup(data: Object) {
this.showPopupEmitter.emit(data);
}
}
彈出組件
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));
}
}
當前狀態是顯示彈出窗口,並且可觀察對象立即被“解析”。 如何通過按鈕“解析”它,以便可以繼續在account.component.ts
使用函數?
您可以嘗試使用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)
每當按下按鈕時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.