RxJS Angular2组件与Observables的交互

时间:2017-02-27 13:21:44

标签: html angular typescript rxjs observable

我正在尝试使用服务使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内继续我的功能?

1 个答案:

答案 0 :(得分: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)

每当按下按钮时。