NavCtrl.push无法在设备上工作,但在Ionic 2的浏览器中工作

时间:2018-03-22 11:53:04

标签: ionic2 ionic3

当我在浏览器上运行时,“立即购买”和“添加到购物车”按钮工作正常但是当我在设备上安装应用程序时,当我点击“立即购买”按钮时没有任何反应添加到购物车“按钮。除了两个按钮(“立即购买”和“添加到购物车”)外,所有按钮都正常工作。这是代码:

HTML:

    <ion-row col-12 class="float-button">
    <ion-col col-6>
      <button ion-button block color="orange" (click)="goToAddressPage(product,prodquantity)">Buy Now</button>
    </ion-col>
    <ion-col col-6>  
      <button  ion-button block color="triams" (click)="addToCart()">Add to Cart</button>
    </ion-col>
  </ion-row>

TS:

    goToAddressPage(product,prodquantity) {

    this.storage.ready()
    .then(()=>{
      this.storage.get('isLogin')
      .then((data)=>{
        this.log = data;

          if(this.log == true) {
            if(this.datastock == 0) {
              this.showPopup("In Stock Soon", "The item is currently sold out.");
            }else if(this.datastock >= 1 && this.datastock < this.prodquantity) {
              this.showPopup("Sorry", "You can only avail a maximum of " + this.datastock + " piece(s) of this item");                 
            }else {
              this.navCtrl.push(AddressPage, { product: product ,prodquantity: prodquantity });
              this.prodquantity = 1;
            }
          } else if(this.log == false){
            this.navCtrl.push(LoginPage);
            this.showPopup("Oops!", "You must login first before you proceed.");
          }
      })
    })

  }

APP.MODULE.TS

import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { HttpModule } from '@angular/http';
import { MyApp } from './app.component';
import { Network } from '@ionic-native/network';
import { PayPal } from '@ionic-native/paypal';

import { IonicStorageModule } from '@ionic/storage';
import { DatePipe } from '@angular/common';

import { AddressPage } from '../pages/address/address';
import { CartPage } from '../pages/cart/cart';
import { CartpaymentPage } from '../pages/cartpayment/cartpayment';
import { CartorderPage } from '../pages/cartorder/cartorder';
import { CartorderpaypalPage } from '../pages/cartorderpaypal/cartorderpaypal';
import { CartpaypalPage } from '../pages/cartpaypal/cartpaypal';
import { CartshippingPage } from '../pages/cartshipping/cartshipping';
import { CategoryPage } from '../pages/category/category';
import { DetailsPage } from '../pages/details/details';
import { EditaddressPage } from '../pages/editaddress/editaddress';
import { ForgotpassPage } from '../pages/forgotpass/forgotpass';
import { HomePage } from '../pages/home/home';
import { MyordersPage } from '../pages/myorders/myorders';
import { MyreturnsPage } from '../pages/myreturns/myreturns';
import { LoginPage } from '../pages/login/login';
import { MyaccountPage } from '../pages/myaccount/myaccount';
import { ProductPage } from '../pages/product/product';
import { OrderPage } from '../pages/order/order';
import { OrderdetailsPage } from '../pages/orderdetails/orderdetails';
import { OrderpaypalPage } from '../pages/orderpaypal/orderpaypal';
import { PaymentPage } from '../pages/payment/payment';
import { PaypalpaymentPage } from '../pages/paypalpayment/paypalpayment';
import { PolicyPage } from '../pages/policy/policy';
import { PopoverPage } from '../pages/popover/popover';
import { ReturnPage } from '../pages/return/return';
import { ReturndetailsPage } from '../pages/returndetails/returndetails';
import { ReviewPage } from '../pages/review/review';
import { SearchPage } from '../pages/search/search';
import { SearchresultsPage } from '../pages/searchresults/searchresults';
import { SignupPage } from '../pages/signup/signup';
import { SubcategoryPage } from '../pages/subcategory/subcategory';
import { TabsPage } from '../pages/tabs/tabs';
import { TermsPage } from '../pages/terms/terms';

import { ProviderOneProvider } from '../providers/provider-one/provider-one';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

@NgModule({
  declarations: [
    MyApp,
    AddressPage,
    CartPage,
    CartpaymentPage,
    CartpaypalPage,
    CartorderPage,
    CartorderpaypalPage,
    CartshippingPage,
    CategoryPage,
    DetailsPage,
    EditaddressPage,
    ForgotpassPage,
    HomePage,
    LoginPage,
    MyaccountPage,
    MyordersPage,
    MyreturnsPage,
    ProductPage,
    OrderPage,
    OrderdetailsPage,
    OrderpaypalPage,
    PaymentPage,
    PaypalpaymentPage,
    PopoverPage,
    PolicyPage,
    ReturnPage,
    ReturndetailsPage,
    ReviewPage,
    SignupPage,
    SearchPage,
    SearchresultsPage,
    SubcategoryPage,
    TabsPage,
    TermsPage
  ],
  imports: [
    BrowserModule,
    HttpModule,
    IonicStorageModule.forRoot(),
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AddressPage,
    CartPage,
    CartpaymentPage,
    CartpaypalPage,
    CartorderPage,
    CartorderpaypalPage,
    CartshippingPage,
    CategoryPage,
    DetailsPage,
    EditaddressPage,
    ForgotpassPage,
    HomePage,
    LoginPage,
    MyaccountPage,
    MyordersPage,
    MyreturnsPage,
    PaymentPage,
    PaypalpaymentPage,
    ProductPage,
    OrderPage,
    OrderdetailsPage,
    OrderpaypalPage,
    PopoverPage,
    PolicyPage,
    ReturnPage,
    ReturndetailsPage,
    ReviewPage,
    SignupPage,
    SearchPage,
    SearchresultsPage,
    SubcategoryPage,
    TabsPage,
    TermsPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    ProviderOneProvider,
    DatePipe,
    PayPal,
    Network
  ]
})
export class AppModule {}

Login.TS

import { ProviderOneProvider } from '../../providers/provider-one/provider-one';

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {

  constructor(public datepipe: DatePipe, private alertCtrl: AlertController, public storage: Storage, public viewCtrl: ViewController, public http: Http, public formBuilder: FormBuilder, public loadingCtrl: LoadingController, public dataService: ProviderOneProvider, public modalCtrl: ModalController, public nav: NavController) {

    this.LoginForm = formBuilder.group({
      email: ['', Validators.compose([Validators.required, Validators.minLength(6),Validators.pattern(/^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i)])],
      password: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
      contactno: [],
      vcode: []
    });

    this.storage.ready()
    .then(()=>{
      this.storage.get('isLogin')
      .then((data)=>{
        this.active = data;
      })
    })

    this.storage.ready()
    .then(()=>{
      this.storage.get('customer')
      .then((data)=>{
        this.store = data;
      })
    })

  }

  ionViewDidEnter() {

    let loader = this.loadingCtrl.create({
                     content: "Please wait ..."
                });
    loader.present();

    this.storage.ready()
    .then(()=>{
      this.storage.get('isLogin')
      .then((data)=>{
        this.active = data;
      })
    })

    this.storage.ready()
    .then(()=>{
      this.storage.get('customer')
      .then((data)=>{
        this.store = data;
        loader.dismiss();
      })
    })

    this.date = Date.now();
    this.date = this.datepipe.transform(this.date, 'yyyy-MM-dd');
    console.log(this.date);
    this.emaillog = "";
    this.passlog = "";
    this.customer_active = false;
    this.customerStatus = false;
    this.customerDeactivated = false;
  }

  createAccount() {
    let createAccount = this.modalCtrl.create(SignupPage);
     createAccount.present();
  }

  login() {

   this.submitAttempt == true;
   if(this.LoginForm.valid) {

       let loginData = { email: this.LoginForm.value.email, password: this.LoginForm.value.password };
          let loader = this.loadingCtrl.create({
              content: "Please wait ..."
          });
          loader.present();
          this.dataService.login(loginData).then((result) => {
          this.LoginData = result;
          loader.dismiss();

          if (Object.prototype.hasOwnProperty.call(this.LoginData, 'customer')) {
              this.customerStatus = true;
              this.customer_active = false;
              this.customerDeactivated = false;
          } else if (Object.prototype.hasOwnProperty.call(this.LoginData, 'cus_active')) {
              console.log("Email Address: " +this.emaillog);
              this.customerStatus = false;
              this.customer_active = true;
              this.customerDeactivated = false;
                let loader = this.loadingCtrl.create({
                     content: "Please wait ..."
                });
                loader.present();
                this.http.get('http://capstone20172018.xyz/TOMS/api.php/customer?filter=customer.customer_email_address,eq,'+this.emaillog+'&transform=1')
                  .map(res => res.json())
                  .subscribe(data => {
                      loader.dismiss();
                      this.validcustomer = data.customer;
                      this.id = this.validcustomer[0].customer_id;
                      this.cuscode = this.validcustomer[0].customer_validation_code;
                      this.contactno = this.validcustomer[0].customer_contact_no;
                      console.log("Verification Code DB: " +this.cuscode);
                  }, (err) => {
                      console.log("Something went wrong." +err);
                });
          } else if (Object.prototype.hasOwnProperty.call(this.LoginData, 'customer_deactivated')) {
              this.customerDeactivated = true;
              this.customerStatus = false;
              this.customer_active = false;
          } else if (Object.prototype.hasOwnProperty.call(this.LoginData, 'customer_block')) {
              this.customerDeactivated = false;
              this.customerStatus = false;
              this.customer_active = false;
              this.showPopup("Sorry","Your account is temporarily block");
          } else {
              this.storage.ready().then(() => {
              this.storage.set('customer', this.LoginData);
              this.storage.set('isLogin', true);

                let loader = this.loadingCtrl.create({
                     content: "Please wait ..."
                });
                loader.present();

                this.storage.ready()
                  .then(()=>{
                    this.storage.get('customer')
                    .then((data)=>{
                      this.store = data;
                      this.active = true;
                      loader.dismiss();
                    }, (err) =>{
                      console.log("Something went wrong. " +err);
                      loader.dismiss();
                    })
                  })

              });
          }
        });
  } else {
    this.required = true;  
  }
}

 logout() {

  let loader = this.loadingCtrl.create({
            content: "Please wait ..."
        });
        loader.present();
        this.storage.ready().then(() => {
          this.storage.remove('customer')
          this.storage.set('isLogin', false)
          this.store = null;
          this.emaillog = "";
          this.passlog = "";
          loader.dismiss();
    });
 }

 forgotPass() {
  this.nav.push(ForgotpassPage);
 }

 activate(customer) {

  let loader = this.loadingCtrl.create({
        content: "Please wait ..."
    });
    loader.present();

    if(this.mycode==this.cuscode) {

        this.http.put('http://apiURL/xxx/api.php/customer/'+this.id, JSON.stringify(this.activated))
          .subscribe(res => {
            this.showPopup("Success","Account Activated.");
            this.customer_active = false;
            loader.dismiss();
          }, (err) => {
            console.log(err);
            this.showPopup("Oops!", "Something went wrong.");
            loader.dismiss();
          });

    }else {
      this.wrongcode = true;
      loader.dismiss();
    }

 }

 resendCode() {

    let signupData = { contactno: this.LoginForm.value.contactno, email: this.LoginForm.value.email, code: this.LoginForm.value.vcode };
    this.dataService.notif(signupData)
    .then((result) => {
      console.log(result);
      this.showPopup("Success","Verification Code successfully sent.");
    }, (err) => {
      console.log(err);
    });
 }

  showPopup(title, text) {
    let alert = this.alertCtrl.create({
      title: title,
      subTitle: text,
      buttons: [
        {
          text: 'OK',
          handler: data => {
            if (this.createSuccess) {
              this.nav.popToRoot();
            }
          }
        }
      ]
    });
    alert.present();
  }

}

1 个答案:

答案 0 :(得分:0)

您需要更改goToAddressPage(product,prodquantity)功能

   goToAddressPage(product,prodquantity) {

    this.storage.ready()
    .then(()=>{
      this.storage.get('isLogin')
      .then((data)=>{
        this.log = data;

          if(this.log == true) {
            if(this.datastock == 0) {
              this.showPopup("In Stock Soon", "The item is currently sold out.");
            }else if(this.datastock >= 1 && this.datastock < this.prodquantity) {
              this.showPopup("Sorry", "You can only avail a maximum of " + this.datastock + " piece(s) of this item");                 
            }else {
              this.prodquantity = 1;
              this.navCtrl.push(AddressPage, { product: product ,prodquantity: prodquantity });

            }
          } else if(this.log == false){
            this.showPopup("Oops!", "You must login first before you proceed.");
            this.navCtrl.push(LoginPage);
          }
      })
    })

  }

重构Login.ts代码。对于最佳实践而言,这不是错误

import { ProviderOneProvider } from '../../providers/provider-one/provider-one';

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {

  constructor(public datepipe: DatePipe, private alertCtrl: AlertController, public storage: Storage, public viewCtrl: ViewController, public http: Http, public formBuilder: FormBuilder, public loadingCtrl: LoadingController, public dataService: ProviderOneProvider, public modalCtrl: ModalController, public nav: NavController) {

    this.LoginForm = formBuilder.group({
      email: ['', Validators.compose([Validators.required, Validators.minLength(6),Validators.pattern(/^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i)])],
      password: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
      contactno: [],
      vcode: []
    });

    this.storage.ready()
    .then(()=>{
      this.storage.get('isLogin')
      .then((data)=>{
        this.active = data;
      });

      this.storage.get('customer')
      .then((data)=>{
        this.store = data;
      });
    })


  }