如何更改app.component.ts中的项目?

时间:2018-09-23 00:02:22

标签: ionic-framework ionic3

我正在Ionic上开发一个项目,登录后,我确实设置了app.component.ts中使用的storage('id')来获取用户详细信息,但是当我运行代码时,它不起作用,但是当我重新加载整个页面(Ctrl + R)时,它就会起作用。

这是我的代码。

login.ts:

import {Component} from "@angular/core";
import {NavController, AlertController, ToastController, MenuController} from "ionic-angular";
import {HomePage} from "../home/home";
import {RegisterPage} from "../register/register";
import { ServicesProvider } from '../../providers/services/services';
import { Storage } from '@ionic/storage';

@Component({
    selector: 'page-login',
    templateUrl: 'login.html'
})
export class LoginPage {
    private user = {
        email: '',
        password: ''
    }
    private setputt:string;
    constructor(public navCtrl: NavController, 
        public forgotCtrl: AlertController, 
        public menu: MenuController, 
        public toastCtrl: ToastController,
        private storage: Storage, 
        public ServicesProvider: ServicesProvider
    ) {
        this.menu.swipeEnable(false);
    }

    register() {
        this.navCtrl.setRoot(RegisterPage);
    }

    login(user){
        this.ServicesProvider.loginpost(user).subscribe(
            data => {
                if(data.success){
                    this.setputt = data.message;
                    if(this.setputt == 'Login Successfull'){                        
                        this.storage.set('id', data.id);
                        this.navCtrl.setRoot(HomePage); 
                    }
                }
                else{
                    this.setputt = data.message;
                }
            },
            error => {
                console.log(error);
            }
        )
    }
    // set a key/value
    //   storage.set('name', 'Max');

    // // Or to get a key/value pair
    // storage.get('age').then((val) => {
    //  console.log('Your age is', val);
    // });
    // storage.remove('name');

    forgotPass() {
        let forgot = this.forgotCtrl.create({
            title: 'Forgot Password?',
            message: "Enter you email address to send a reset link password.",
            inputs: [
            {
                name: 'email',
                placeholder: 'Email',
                type: 'email'
            },
            ],
            buttons: [
            {
                text: 'Cancel',
                handler: data => {
                console.log('Cancel clicked');
                }
            },
            {
                text: 'Send',
                handler: data => {
                console.log('Send clicked');
                let toast = this.toastCtrl.create({
                    message: 'Email was sended successfully',
                    duration: 3000,
                    position: 'top',
                    cssClass: 'dark-trans',
                    closeButtonText: 'OK',
                    showCloseButton: true
                });
                toast.present();
                }
            }
            ]
        });
        forgot.present();
    }

}

app.component.ts:

    import { Component, ViewChild } from '@angular/core';
    import { Platform, Nav } from 'ionic-angular';
    import { StatusBar } from '@ionic-native/status-bar';
    import { SplashScreen } from '@ionic-native/splash-screen';
    import { Storage } from '@ionic/storage';
    import { ServicesProvider } from '../providers/services/services'; 

    import { HomePage } from '../pages/home/home';
    import {LoginPage} from "../pages/login/login";
    import {ProfilePage} from "../pages/profile/profile";
    import {FriendsPage} from "../pages/friends/friends";
    import {YearbooksPage} from "../pages/yearbooks/yearbooks"; 
    import {ChatPage} from "../pages/chat/chat";
    import {FilesPage} from "../pages/files/files";
    import {CheckLoginPage} from "../pages/check-login/check-login";

    export interface MenuItem {
      title: string;
      component: any;
      icon: string;
    }
    @Component({
        templateUrl: 'app.html'
    })
    export class MyApp {
        @ViewChild(Nav) nav: Nav;

        rootPage: any = CheckLoginPage; 
        appMenuItems: Array<MenuItem>;
        public FullNamer;
        public pixr;
        public id:number;
        constructor(
            platform: Platform, 
            statusBar: StatusBar, 
            splashScreen: SplashScreen, 
            public storage: Storage,
            public ServicesProvider: ServicesProvider
        ) {
            platform.ready().then(() => {
                statusBar.styleDefault();
                splashScreen.hide();
            });
            this.storage.get('id').then((vals) => {
                if (vals != null) {
                    this.ServicesProvider.getDetails(vals).subscribe(data=>{
                        // console.log(data); 
                        this.pixr = this.ServicesProvider.theurl+data.pix;
                        this.FullNamer = data.fullname;
                    });
                }
            });

            this.appMenuItems = [
                {title: 'Home', component: HomePage, icon: 'home'},
                {title: 'Files', component: FilesPage, icon: 'ios-folder'},
                {title: 'Friends', component: FriendsPage, icon: 'ios-people'},
                {title: 'Yearbooks', component: YearbooksPage, icon: 'ios-book'},
                {title: 'Chat', component: ChatPage, icon: 'md-chatbubbles'}
            ];
        } 
        ionViewCanEnter(){

        }
        openPage(page) {
            this.nav.setRoot(page.component);
        }
        GoPages(){
            this.nav.setRoot(ProfilePage);
        }
        logout() {
            this.storage.remove('id');
            this.storage.remove('FullName');
            this.nav.setRoot(LoginPage);
        }
    }

app.html

<ion-menu side="left" id="authenticated" [content]="content">
  <ion-header>
    <ion-toolbar class="user-profile">

      <ion-grid>
        <ion-row>
          <ion-col col-4>
              <div class="user-avatar">
                <img [src]="pixr"> 
              </div>
          </ion-col>
          <ion-col padding-top col-8>
              <h2 ion-text class="no-margin bold text-white">
                  {{FullNamer}} 
              </h2>
              <span ion-text color="light">Customer</span>
          </ion-col>
        </ion-row>

        <ion-row no-padding class="other-data">
          <ion-col no-padding class="column">
            <button ion-button icon-left small full class="round" color="light" menuClose  (click)="GoPages()">
              <ion-icon name="ios-person"></ion-icon>
              Edit Profile
            </button>
          </ion-col>
          <ion-col no-padding class="column">
            <button ion-button icon-left class="round" small full color="light" menuClose (click)="logout()">
              <ion-icon name="log-out"></ion-icon>
              Log Out
            </button>
          </ion-col>
        </ion-row>

      </ion-grid>

    </ion-toolbar>
  </ion-header>

  <ion-content color="primary">

    <ion-list class="user-list">
      <button ion-item menuClose class="text-1x" *ngFor="let menuItem of appMenuItems" (click)="openPage(menuItem)">
        <ion-icon item-left [name]="menuItem.icon" color="primary"></ion-icon>
        <span ion-text color="primary">{{menuItem.title}}</span>
      </button>
    </ion-list>
  </ion-content>

</ion-menu>

<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>

service.ts:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage';

@Injectable()
export class ServicesProvider {
    public theurl = 'http://localhost/HoleeSheet/php/';
    public tittle = 'Holee Sheet';
    public id:number;
    constructor(public http: HttpClient, private storage: Storage) {
        this.storage.get('id').then((valr) => {
            if (valr != null) {
                this.id = valr;
            }
        });
    }

    loginpost(user){
        return this.http.put<obbbbs>(this.theurl+'login.php', {
            email: user.email,
            password: user.password
        });         
    }
    getDetails(humid){
        console.log(humid);
        return this.http.post<details>(this.theurl+'getDetails.php', {
            id: humid
        });
    }
}
interface details{
    'fullname': string,
    'pix':string
}
interface obbbbs {
    'success': 'boolean',
    'message': 'string',
    'id': 'string'
}

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

欢迎堆栈溢出。

// LoginPage.login method (login.ts)
this.storage.set('id', data.id);
this.navCtrl.setRoot(HomePage); 

在将值保存到存储之前,您正在导航到主页。您应等待this.storage.set返回的诺言得到解决,然后才能继续导航:

// LoginPage.login method (login.ts)
this.storage.set('id', data.id)
    .then(() => this.navCtrl.setRoot(HomePage));