ionic+cordova

1.21 ionic3入门——返回上一页面并刷新

2018-10-01  本文已影响0人  杨啊杨_fb52

在我们实际使用中往往有这么一种需求:当你进入子页面操作之后,返回要刷新父页面的内容。比如,我做了一个笔记功能,在笔记父页面里(A),内容是我保存的笔记,这个时候我点击添加笔记,跳转到添加笔记页面(B),我写好我的笔记之后点击保存,这个时候跳转回我的笔记父页面,我要父页面的内容显示了我刚刚添加的那一则笔记。
(1)在A页面和B页面中也别引入Events

import { Events } from 'ionic-angular';

并在构造函数中声明

public events: Events

(2)B(子)页面中要跳转的地方添加如下代码

      this.navCtrl.pop().then(()=>{
        this.events.publish('reloadNotePage');
      });

(3)A(父)页面中ionViewDidLoad()添加如下代码

    this.events.subscribe('reloadNotePage',() => {
      this.items = new Array();
      let that = this;
      var localpoi:any[]=new Array();
      this.storage.get('note').then((data)=>{
        if(data==null){
          alert("没有数据");
        }
        else{
          localpoi = data;
          console.log(localpoi);
          for(var i = 0;i<localpoi.length;i++){
            var poi = localpoi[i];
            that.items.push(poi);
          }
        }
      });

(4)父页面ts完整代码

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams,ActionSheetController } from 'ionic-angular';
import { NoteAddPage } from '../note-add/note-add';
import { Storage } from '@ionic/storage';
import { Events } from 'ionic-angular';
/**
 * Generated class for the NotePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

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

  public items:any[] = new Array();

  constructor(public navCtrl: NavController, public navParams: NavParams,private storage:Storage,public events:Events) {
  }

  ionViewDidLoad() {
    this.storage.get('note').then((data)=>{
      this.items = new Array();
      let that = this;
      var localpoi:any[]=new Array();
      if(data==null){
        alert("没有笔记");
      }
      else{
        localpoi = data;
        console.log(localpoi);
        for(var i = 0;i<localpoi.length;i++){
          var poi = localpoi[i];
          that.items.push(poi);
        }
      }
    });

    this.events.subscribe('reloadNotePage',() => {
      this.items = new Array();
      let that = this;
      var localpoi:any[]=new Array();
      this.storage.get('note').then((data)=>{
        if(data==null){
          alert("没有数据");
        }
        else{
          localpoi = data;
          console.log(localpoi);
          for(var i = 0;i<localpoi.length;i++){
            var poi = localpoi[i];
            that.items.push(poi);
          }
        }
      });
    });
  }
  add_note(){
    this.navCtrl.push(NoteAddPage);
  }
}

(5)子页面ts完整代码

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams,ActionSheetController } from 'ionic-angular';

import {Camera, CameraOptions} from '@ionic-native/camera';
import { ImagePicker,ImagePickerOptions } from '@ionic-native/image-picker';
import { Storage } from '@ionic/storage';

import { Events } from 'ionic-angular';

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

declare var BMap;
@IonicPage()
@Component({
  selector: 'page-note-add',
  templateUrl: 'note-add.html',
})
export class NoteAddPage {
  newLeave:any={};
  poi_address:string="";
  user_name:string="";
  imgDiv = document.getElementById('post_img_1');
  public imagesArr = new Array();
  image_num:number=0;





  constructor(public navCtrl: NavController, private storage:Storage,public navParams: NavParams,public events: Events,public actionSheetCtrl: ActionSheetController,private camera: Camera,
    private imagePicker: ImagePicker,) {
      //this.newLeave.sqsj=new Date().toISOString();//获取当前时间 这个是零度经线的时间 相差八个小时
      this.newLeave.sqsj=new Date(new Date().getTime()+8*60*60*1000).toISOString();//北京时间
      var lat=localStorage.getItem("my_latitude");
      var lng=localStorage.getItem("my_longitude");
      this.get_address_bybaidumap(lat,lng);
      
      this.user_name = "杨啊杨";

      
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad NoteAddPage');
  }


  presentActionSheet() {
    let that = this;
    const actionSheet = this.actionSheetCtrl.create({
      
      title: '上传照片',
      buttons: [
        {
          text: '拍照',
          role: 'destructive',
          handler: () => {
            this.openCamera(that);
          }
        },{
          text: '相册选择',
          handler: () => {
            this.pickimg(that);
           
          }
        },{
          text: '取消',
          role: 'cancel',
          handler: () => {
            console.log('Cancel clicked');
          }
        }
      ]
    });
    actionSheet.present();
  }



    openCamera(that) {
        const options: CameraOptions = {
        quality: 70,                                                   // 相片质量 0 -100
        destinationType: this.camera.DestinationType.DATA_URL,        // DATA_URL 是 base64   FILE_URL 是文件路径
        encodingType: this.camera.EncodingType.JPEG,
        mediaType: this.camera.MediaType.ALLMEDIA,   //有PICTURE VIDEO ALLMEDIA
        saveToPhotoAlbum: true,                                       // 是否保存到相册
        sourceType: this.camera.PictureSourceType.CAMERA ,         //是打开相机拍照还是打开相册选择  PHOTOLIBRARY : 相册选择, CAMERA : 拍照,
      }

      this.camera.getPicture(options).then((imageData) => {
        console.log('got file: ' + imageData);

          // If it's base64:
         let base64Image = 'data:image/jpeg;base64,' + imageData;
         
         this.add_img(base64Image);

        that.imagesArr.push(base64Image);
        that.imagesDataArr.push(imageData);
        //alert(that.imagesArr.length);

        // If it's file URI
        // this.path = imageData;
        // this.upload();

      }, (err) => {
        //alert(err);
        // Handle error
      });
  }




  //安卓用不了这个 我还是直接用相机的看看吧~
  pickimg(that){
    
    var u = navigator.userAgent;
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
    if(isiOS==true){
      this.ios_pick_img(that);
    }
    if(isAndroid==true){
      this.android_pick_img(that);
    }

  
  
  }

  android_pick_img(that){
      const options: CameraOptions = {
      quality: 60,                                                   // 相片质量 0 -100
      destinationType: that.camera.DestinationType.DATA_URL,        // DATA_URL 是 base64   FILE_URL 是文件路径
      encodingType: that.camera.EncodingType.JPEG,
      mediaType: that.camera.MediaType.PICTURE,   //有PICTURE VIDEO ALLMEDIA
      saveToPhotoAlbum: true,                                       // 是否保存到相册
      sourceType: that.camera.PictureSourceType.PHOTOLIBRARY ,         //是打开相机拍照还是打开相册选择  PHOTOLIBRARY : 相册选择, CAMERA : 拍照,

    }

    that.camera.getPicture(options).then((imageData) => {
      console.log('got file: ' + imageData);

       // If it's base64:
       let base64Image = 'data:image/jpeg;base64,' + imageData;
       
      that.add_img(base64Image);

      that.imagesArr.push(base64Image);
      that.imagesDataArr.push(imageData);
      //alert(that.imagesArr.length);

      // If it's file URI
      // this.path = imageData;
      // this.upload();

    }, (err) => {
      //alert(err);
      // Handle error
    });

  }
  ios_pick_img(that){
    const options:ImagePickerOptions ={
        maximumImagesCount:9-that.image_num,
      quality:50,
      outputType : 1  //默认为0,返回类型为file_url;为1,返回值为base64-encoded string
    };
    that.imagePicker.getPictures(options).then((results) => {
        for (var i = 0; i < results.length; i++) {
      
       let base64Image = 'data:image/jpeg;base64,' + results[i];
       
     
       that.add_img(base64Image);
      
       that.imagesArr.push(base64Image);
       that.imagesDataArr.push(results[i]);
       

          // 保存图片到html控件
          // var imgUrl = "<img src=" +results[i] +" width=\"60px\" height=\"60px\">  ";
          //this.data=this.data+imgUrl;

        }
      }, (err) => { 
        alert('未进行照片选取~');
        //alert(err);
    });

  }

  change_img_style(){
    alert(this.imgDiv.offsetWidth+'px');
    this.imgDiv.style.height=this.imgDiv.offsetWidth+'px';
  }

  test_click_img(){
    this.imagesArr.push("assets/imgs/monkey.jpg");
    this.imagesArr.push("assets/imgs/noimg.jpg");
    this.add_img("assets/imgs/monkey.jpg");
    this.add_img("assets/imgs/noimg.jpg");
  }

  add_img(image_src){
    
    
    var that = this;
    this.image_num++;
         // function allscreen(navigator){
         //  that.statusBar.hide();
         // }
         //增加image
         var div = document.createElement("div");
         div.className="image_div";
         //var img = new Image();
         var img=new Image();
         img.className="small_img";
         img.src=image_src;
         div.appendChild(img);
         img.onclick=function(navigator){
          
          var bigImage_father=document.getElementById('bigImage_father');
            var big_image_Div=document.getElementById('bigImage');
          var big_image_Div_img=document.getElementById('bigImage_img');
          var delete_img_button=document.getElementById('delete_img_button');
          big_image_Div.removeChild(big_image_Div_img);

            bigImage_father.hidden=false;
            var img1=new Image();
            img1.className="big_img";
            img1.src=image_src;
          img1.id="bigImage_img";


            big_image_Div.appendChild(img1);

          bigImage_father.removeChild(delete_img_button);
          bigImage_father.appendChild(delete_img_button);


          //点击删除按钮 删除图片 并关闭大图
          delete_img_button.onclick=function(){

            div.parentNode.removeChild(div);
            bigImage_father.hidden=true;
            
            that.image_num--;
            that.change_add_img_btn();
            that.imagesArr[that.imagesArr.indexOf(image_src)]=null;
            //typescript完全删除元素是splice,太他妈麻烦,所以用伪删除 将要删除的元素设置为null 到时候判断的时候可不要忘记了哦~~
            //that.imagesArr.remove(image_src);
            //(that.imagesArr.length);
          }

          //点机大图,关闭大图 
            img1.onclick=function(){
                bigImage_father.hidden=true;
            };

            
         };
         var fatherDiv=document.getElementById('my_image_div_father');
         fatherDiv.appendChild(div);
         this.change_add_img_btn();
         
  }
  change_add_img_btn(){
         if(this.image_num<9){
           //删除原有的
           var add_img_btn = document.getElementById("add_img_button_div");
           var add_image_div = document.getElementById("post_img_0");      
           //新增
           var div = document.createElement("div");
           div.id="add_img_button_div";
           div.className="image_div";
           div.appendChild(add_image_div);
           add_img_btn.parentNode.removeChild(add_img_btn);
           var fatherDiv=document.getElementById('my_image_div_father');
           fatherDiv.appendChild(div);       
         }
         else{
           var add_img_btn = document.getElementById("add_img_button_div");
           add_img_btn.hidden=true;
         }

  }



  //百度地图地理逆编码
  get_address_bybaidumap(x,y){
    let that = this;
    //原始GPS坐标转为百度坐标
    var baiduPoint = new BMap.Point(y,x);
    var myGeo = new BMap.Geocoder();
    myGeo.getLocation(baiduPoint,function(result){
        if(result){
            var address = result.addressComponents.province+'-'+result.addressComponents.city+'-'+result.addressComponents.district+
            '-'+result.addressComponents.street+'-'+result.addressComponents.streetNumber;
            localStorage.removeItem("poi_address");
        localStorage.setItem("poi_address",address);
        // that.poi_province=result.addressComponents.province;
        // that.poi_city=result.addressComponents.city;
        // that.poi_district=result.addressComponents.district;
        // that.poi_street=result.addressComponents.street;
        // that.poi_streetnumber=result.addressComponents.streetNumber;
        alert(address);
        }
    });
    var address = localStorage.getItem("poi_address");
    this.poi_address=address;
    
  }

  save(note_title:HTMLInputElement,note_content:HTMLInputElement,date:HTMLInputElement,address:HTMLInputElement,recoder:HTMLInputElement){
    var title: string = note_title.value;
    var content:string=note_content.value;
    var note_date=date.value;
    var note_address:string=address.value;
    var note_recoder:string=recoder.value;

    //剔除原来照片数组的null值
    var new_image_arr:any[]=new Array();
    for(var i = 0;i<this.imagesArr.length;i++){
      if(this.imagesArr[i]==null){
      }
      else{
        new_image_arr.push(this.imagesArr[i]);
      }
    }
    var new_image_arr_string = JSON.stringify(new_image_arr);
    var date_str =JSON.stringify(note_date);
    //note对象
    var note ={
      'title':title,
      'content':content,
      'date':date_str,
      'address':note_address,
      'recoder':note_recoder,
      'imgs':new_image_arr_string,
    }
    this.storage.get('note').then((data)=>{
      if(data==null){
        data=[];
      }
      data.push(note);
      this.storage.set('note',data);
      alert("保存成功");
      this.navCtrl.pop().then(()=>{
        this.events.publish('reloadNotePage');
      });
    });
  }

}


![跳转.gif](https://img.haomeiwen.com/i13686636/be85cf46b3b77a40.gif?imageMogr2/auto-orient/strip)





上一篇下一篇

猜你喜欢

热点阅读