CanDeactivate在Angular 6中无法正常工作

时间:2018-08-10 14:50:13

标签: javascript angular

这是我的付款component.ts,我在其中使用了Candeactivate,这样,只要用户尝试从此组件移至其他组件,我都会收到提示。它的工作正常,现在的问题是,当用户完成付款并且当我尝试转到其他页面时,它会询问相同的提示

import { Component, OnInit } from '@angular/core';
import { PayPalConfig, PayPalEnvironment, PayPalIntegrationType } from 'ngx-paypal';
import { AppService } from '../app.service';
import { Payment } from '../models/payment.model';
import { Router } from '@angular/router';
@Component({
  selector: 'app-payment',
  templateUrl: './payment.component.html',
  styleUrls: ['./payment.component.css']
})
export class PaymentComponent implements OnInit {
//totalpay:number;
payment:Payment;
changesSaved=false;
  constructor(private appservice:AppService,private router:Router) { }

  ngOnInit() {
    this.initConfig();

   }


  public payPalConfig?: PayPalConfig;

hasChanges(){
  //return true;
  return this.changesSaved;

}    
  private initConfig(): void {
    this.changesSaved=true;//making changes saved true here
    console.log(this.changesSaved); // it prints true
    this.payPalConfig = new PayPalConfig(PayPalIntegrationType.ClientSideREST, PayPalEnvironment.Sandbox, {
      commit: true,
      client: {
        sandbox: 'AZDxjDScFpQtjWTOUtWKbyN_bDt4OgqaF4eYXlewfBP4-8aqX3PiV8e1GWU6liB2CUXlkA59kJXE7M6R'
      },
      button: {
        label: 'paypal',
      },
      onPaymentComplete: (data, actions) => {


        console.log("success");
        console.log(data);
        //storing customerid from session token as well
        this.payment={customerid:this.appservice.getcarttoken(),intent:data.intent,orderID:data.orderID,payerID:data.payerID,paymentID:data.paymentID,paymentToken:data.paymentToken,billingid:"NA",status:"Payment Success"}
        this.appservice.paypalpayment(this.payment).subscribe( 
          data => {
          console.log(data);

        },
        error => { console.log(error); // Error if any
        },
        ()=> {
          this.appservice.removeall();//removing cart so that we can start afresh

          this.router.navigate(['/orderstatus']);
        }
      )
      },
      onCancel: (data, actions) => {
        //this.changesSaved=true;
        console.log("Cancel");
        console.log(data);
       this.payment={customerid:this.appservice.getcarttoken(),intent:"sale",orderID:"NA",payerID:"NA",paymentID:"User Cancelled", paymentToken:"User Cancelled",billingid:"NA",status:"Payment Failed"}
        this.appservice.paypalpayment(this.payment).subscribe( 
          data => {
          console.log(data);

        },
        error => { 
          console.log(error); // Error if any
        },
        ()=> {
          //this.appservice.removeall();//removing cart so that we can start afresh

          this.router.navigate(['/paymentfail']);
        }
      )
        console.log(data);
        //this.appservice.paymentstatus("success",data.intent,data.orderID,data.payerID,data.paymentID,data.paymentToken);
      },
      onError: (err) => {
        console.log("Error");
        console.log(err);
      },
      transactions: [{
        amount: {
          currency: 'USD',
          total:this.appservice.gettotalcartvalue()
        }
      }]
    });
  }
}

这是我的付款保管员。

import { Injectable } from '@angular/core';
import { CanDeactivate } from '@angular/router';
import { Observable } from 'rxjs';

import { PaymentComponent } from './payment/payment.component';
import { CartComponent } from './cart/cart.component';
@Injectable() 
export class CanDeactivateGuard implements CanDeactivate<PaymentComponent> {
  canDeactivate(target: PaymentComponent): Observable<boolean> { 
    return Observable.create(function(observer) {
      if (!target.hasChanges()) {
        observer.next(true);
      } else if(window.confirm('Do you really want to cancel?')) {
        observer.next(true);
      } 
      else {
        observer.next(false);
      }
    });
  } 
}

即使将变量更改为true,我也无法更改路线,为什么不起作用?

1 个答案:

答案 0 :(得分:1)

  

执行此操作,请参见代码中的注释

canDeactivate(target: PaymentComponent): Observable<boolean> { 
    return Observable.create(function(observer) {
      if (target.hasChanges()) {// removed not from here
        observer.next(true);
      } else if(window.confirm('Do you really want to cancel?')) {
        observer.next(true);
      } 
      else {
        observer.next(false);
      }
    });
  } 
}


  onPaymentComplete: (data, actions) => {
        this.changesSaved=true;// change the variable here
        console.log(this.changesSaved);


        console.log("success");
        console.log(data);
        //storing customerid from session token as well
        this.payment={customerid:this.appservice.getcarttoken(),intent:data.intent,orderID:data.orderID,payerID:data.payerID,paymentID:data.paymentID,paymentToken:data.paymentToken,billingid:"NA",status:"Payment Success"}
        this.appservice.paypalpayment(this.payment).subscribe( 
          data => {
          console.log(data);

        },
        error => { console.log(error); // Error if any
        },
        ()=> {
          this.appservice.removeall();//removing cart so that we can start afresh

          this.router.navigate(['/orderstatus']);
        }
      )
      },
      onCancel: (data, actions) => {
        this.changesSaved=true;// change the variable here
        console.log(this.changesSaved);
        //this.changesSaved=true;
        console.log("Cancel");
        console.log(data);
       this.payment={customerid:this.appservice.getcarttoken(),intent:"sale",orderID:"NA",payerID:"NA",paymentID:"User Cancelled", paymentToken:"User Cancelled",billingid:"NA",status:"Payment Failed"}
        this.appservice.paypalpayment(this.payment).subscribe( 
          data => {
          console.log(data);

        },

由于您在ngoninit()中调用了付款配置,因此它最初将值设置为true。希望对您有所帮助