02-ionic编写登录以及用户昵称更改教程

版权声明: https://blog.csdn.net/weixin_41404460/article/details/82148914

继续上次的01 ionic教程更新

附上源码地址:

https://pan.baidu.com/s/1wNHUVe2qcKjwSWv4DTqzIQ

注意:node.js建议安装最新版,然后安装Storage,才可以运行ionic serve

在上次的案例代码基础上新增一个pages,name is user.-

user.html源码:

<!--
  Generated template for the UserPage page.

  See http://ionicframework.com/docs/components/#navigation for more info on
  Ionic pages and navigation.
-->
<ion-header>

  <ion-navbar>
    <ion-title>个人中心</ion-title>
  </ion-navbar>

</ion-header>


<ion-content>

  <ion-list class="margin_top">
    <button ion-item>
      <ion-avatar item-start>
        <img src="{{headface}}" />
      </ion-avatar>
      <h2>修改头像</h2>
      <p>查看个人主页或剪辑简介</p>
    </button>

  </ion-list>

  <ion-list>
    <ion-item>
      <ion-label>用户昵名</ion-label>
      <ion-input type="text" [(ngModel)]="nickname"></ion-input>
    </ion-item>

  </ion-list>
  <div class="mypadding">
    <button ion-button color="primary" block (click)="updatenickname()">保存</button>
  </div>
  <div class="mypadding">
    <button ion-button color="danger" block (click)="logout()">注销</button>
  </div>
</ion-content>

user.ts:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ModalController, LoadingController,ToastController,ViewController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import { BaseUI } from '../../common/baseui';
import { RestProvider } from '../../providers/rest/rest';


/**
 * Generated class for the UserPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

// @IonicPage()
@Component({
  selector: 'page-user',
  templateUrl: 'user.html',
})
export class UserPage extends BaseUI {
  headface: string = "assets/imgs/mr.jpg";
  nickname: string = "加载中...";
  errorMessage: string;

  constructor(public navCtrl: NavController, public navParams: NavParams,
    public modalCtrl: ModalController,
    public loadingCtrl: LoadingController,
    public rest: RestProvider,
    public toastCtrl : ToastController,
    public viewCtrl: ViewController,
    private storage: Storage) {
    super();
  }

  ionViewDidLoad() {
    this.loadUserPage();
  }

  loadUserPage() {
    this.storage.get('UserId').then((val) => {
      // console.log('Your age is', val);
      if (val != null) {
        //加载用户数据
        var loading = super.showLoading(this.loadingCtrl, "加载中...");
        this.rest.getUserInfo(val).subscribe(
          userinfo => {
            this.nickname = userinfo["UserNickName"];
            this.headface = userinfo["UserHeadface"] + "?" + (new Date()).valueOf();

            loading.dismiss();

          }, error => this.errorMessage = <any>error);
      }
    });

  }

  updatenickname() {
    this.storage.get('UserId').then((val) => {
      if (val != null) {
        //加载用户数据
        var loading = super.showLoading(this.loadingCtrl, "修改中...");
        this.rest.updatenickname(val,this.nickname).subscribe(
          f => {
            if(f["Status"]=="OK"){
              // this.nickname = f["UserNickName"];
              // this.headface = f["UserHeadface"] + "?" + (new Date()).valueOf();
  
              loading.dismiss();
              super.showToast(this.toastCtrl,"昵称修改成功.");
            }else{
              loading.dismiss();
              // super.showToast(this.toastCtrl,"修改失败");
              //一般错误出现在后端了,以防万一。
              super.showToast(this.toastCtrl,f["StatusContent"]);
            }
          }, error => this.errorMessage = <any>error);
      }
    })
  }

  logout(){
    this.storage.remove("UserId");
    this.viewCtrl.dismiss();
  }

}

rest.ts更新代码:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Http, Response } from '@angular/http';

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';


/*
  Generated class for the RestProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class RestProvider {

  constructor(public http: Http) {
    // console.log('Hello RestProvider Provider');
  }

  //feed
  private apiUrlFeeds = 'https://imoocqa.gugujiankong.com/api/feeds/get';

  //account
  private apiUrlRegister = 'https://imoocqa.gugujiankong.com/api/account/register';
  private apiUrlLogin = 'https://imoocqa.gugujiankong.com/api/account/login';
  private apiUrlUserInfo = 'https://imoocqa.gugujiankong.com/api/account/userinfo';
  private apiUrlUpdateNickName = 'https://imoocqa.gugujiankong.com/api/account/updatenickname';
  private apiGetUserQuestionList = "https://imoocqa.gugujiankong.com/api/account/getuserquestionlist";

  //question
  private apiUrlQuestionSave = 'https://imoocqa.gugujiankong.com/api/question/save';
  private apiUrlQuestionList = 'https://imoocqa.gugujiankong.com/api/question/list?index=1&number=10';
  private apiUrlGetQuestion = "https://imoocqa.gugujiankong.com/api/question/get";
  private apiUrlGetQuestionWithUser = "https://imoocqa.gugujiankong.com/api/question/getwithuser";
  private apiUrlAnswer = "https://imoocqa.gugujiankong.com/api/question/answer";
  private apiUrlSaveFavourite = "https://imoocqa.gugujiankong.com/api/question/savefavourite";

  //notification
  private apiUrlUserNotifications = "https://imoocqa.gugujiankong.com/api/account/usernotifications";


  login(mobile, password): Observable<string[]> {
    return this.getUrlReturn(this.apiUrlLogin + "?mobile=" + mobile + "&password=" + password);

  }
  getUserInfo(userId): Observable<string[]> {
    return this.getUrlReturn(this.apiUrlUserInfo + "?userid=" + userId);
  }

  updatenickname(userId, nickname): Observable<string[]> {
    return this.getUrlReturn(this.apiUrlUpdateNickName + "?userid=" + userId + "&nickname=" + nickname);
  }
  //   /**
  //  * 注册请求
  //  * 
  //  * @param {any} mobile 
  //  * @param {any} nickname 
  //  * @param {any} password 
  //  * @returns {Observable<string[]>} 
  //  * @memberof RestProvider
  //  */
  register(mobile, nickname, password): Observable<string[]> {
    return this.getUrlReturn(this.apiUrlRegister + "?mobile=" + mobile + "&nickname=" + nickname + "&password=" + password)
  }



  private getUrlReturn(url: string): Observable<string[]> {
    return this.http.get(url)
      .map(this.extractDate)
      .catch(this.handleError);

  }

  //处理接口返回的数据,处理成json格式
  private extractDate(res: Response) {
    let body = res.json();
    return JSON.parse(body) || {};
  }

  //处理请求中的错误,考虑了各种情况的错误处理并在console.log中显示error
  private handleError(error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;

    } else {
      errMsg = error.message ? error.message : error.toString()
    }

    console.error(errMsg);
    return Observable.throw(errMsg);
  }

}

值得注意的是之所以要编写

headface: string = "assets/imgs/mr.jpg";

nickname: string = "加载中...";

是因为我需要将他的默认数据进行加载。rest是复用数据函数专用的ts,更新即可。

接下来解决登录过后,登录页面无法刷新进入个人中心问题:

原来more.ts中负责进入登录页面的源码:

 showmodel() {
    const modal = this.modalCtrl.create(LoginPage); 

    modal.present();
  }

改进如下:

 showmodel() {
    const modal = this.modalCtrl.create(LoginPage);

    //关闭后的回调
    //因为modal关闭的时候,不会再次触发父页面的ionViewDidEnter();
    
    modal.onDidDismiss(()=>{
      this.loadUserPage();
    })

    modal.present();
  }

原理已经在注释之中,我的loadUserPage()函数代码如下:

 loadUserPage() {
    this.storage.get('UserId').then((val) => {
      // console.log('Your age is', val);
      if (val != null) {
        //加载用户数据
        var loading = super.showLoading(this.loadingCtrl, "加载中...");
        this.rest.getUserInfo(val).subscribe(
          userinfo => {
            this.userinfo = userinfo;
            this.headface = userinfo["UserHeadface"] + "?" + (new Date()).valueOf();
            this.notlogin = false;
            this.logined = true;

            loading.dismiss();

          }
        );

        // this.notlogin = false;
        // this.logined = true;
        // alert("已登录");
      } else {
        this.notlogin = true;
        this.logined = false;
        // alert("未登录");
      }
    });

  }

ionic的tabs api文档中有写如何返回路由,可是我们这边用的是model,那么就只需要按部就班即可,直接使用onDidDismiss方法将我们的函数重新读取。

感谢各位的解读,望大家收藏。

猜你喜欢

转载自blog.csdn.net/weixin_41404460/article/details/82148914