Angular 2 and TypeScript Promises

后端 未结 5 1497
孤独总比滥情好
孤独总比滥情好 2021-02-03 22:45

I\'m trying to use the routerCanDeactivate function for a component in my app. The simple way to use it is as follows:

routerCanDeactivate() {
             


        
5条回答
  •  时光取名叫无心
    2021-02-03 23:24

    Since everyone is talking about Observables, I figured that I would take a look and build upon @petryuno1's answer.

    Starting with his ModalComponent:

    import {Component, Output, ViewChild} from '@angular/core;
    @Component({
        selector: 'myModal',
        template: `
    ` }) export class MyModal{ private hideModal: boolean = true; private clickStream = new Subject(); @Output() observable = this.clickStream.asObservable(); constructor(){} openModal(){ this.hideModal = false; } closeModal(){ this.hideModal = true; } clickedYes(){ this.clickStream.next(true); } clickedNo(){ this.clickStream.next(false); } }

    Next, we go to the AppComponent:

    import { Component, ViewChild} from '@angular/core';
    import {MyModal} from './myModal';
    import {Subscription} from "rxjs";
    
    @Component({
        ....
        directives: [MyModal]
    })
    
    export class AppComponent {
        @ViewChild(ConfirmModal) confirmModal: ConfirmModal;
        constructor(){...};
    
        public showModal(){
            this.myModal.openModal();
            this.subscription = this.myModal.observable.subscribe(x => {
                console.log('observable called ' + x)
    // unsubscribe is necessary such that the observable doesn't keep racking up listeners
                this.subscription.unsubscribe();
            });
        }
    }
    

    The elegance of observables is that we now get to write a lot less code to do the same thing.

提交回复
热议问题