离子v3在应用程序中进行制造和更新,以更新它在数据库中而不是在应用程序中正在更新的数据

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了离子v3在应用程序中进行制造和更新,以更新它在数据库中而不是在应用程序中正在更新的数据相关的知识,希望对你有一定的参考价值。

我是ionic的新手,我试图了解一个具有基本http查询以与数据库进行通信的应用程序,但是我遇到了问题。有一个页面显示从数据库中获取的列表。在此列表上可以执行两种操作-插入和更新。我尝试进行更新时出现问题。数据库中的记录已更新,但应用程序中的列表未更新。但是,当我插入一条新记录时,列表已更新为新记录,包括所有以前的更改,但未在列表中显示。

这是列表页面的类型脚本:

export class CrudHttpListPage {
  items: any;

  constructor(public loading: LoadingProvider, private toast: ToastProvider, public modal: ModalController, private crud: CrudHttpProvider) { }

  ionViewDidLoad() {
    this.load();
  }

  load() {
    this.loading.present();
    this.crud.read.then(res => {
      this.items = res;
      if (res) this.loading.dismiss();
    });
  }

  add() {
    let modal = this.modal.create('CrudHttpDetailPage', { action: 1 });
    modal.present();
    modal.onDidDismiss(data => {
      console.log(data);
      if (data) this.load();
    });
  }

  edit(item) {
    let modal = this.modal.create('CrudHttpDetailPage', { data: item, action: 2 });
    modal.present();
    modal.onDidDismiss(data => {
      if (data) this.load();
    });
  }

这是添加和编辑页面的打字稿代码:

export class CrudHttpDetailPage {
  private form: FormGroup;
  action: number;
  data: any = { title: '', text: '' };

  constructor(private view: ViewController, private toast: ToastProvider, private loading: LoadingProvider, private crud: CrudHttpProvider, private fb: FormBuilder, public params: NavParams) {
    this.action = params.data.action;
    this.data = params.data && params.data.data || this.data;
    console.log(params.data);

    this.form = this.fb.group({
      id: [this.data && this.data.id],
      title: [this.data && this.data.title, Validators.required],
      text: [this.data && this.data.text, Validators.required]
    });
  }

  submit() {
    this.loading.present();
    console.log(this.form.value);
    this.crud.save(this.form.value).then(data => {
      // this.dataNotes.id = data;
      console.log(data);
      this.loading.dismiss();
      this.view.dismiss(this.form.value);
    }, err => {
      console.log(err);
      this.loading.dismiss();
      this.toast.showWithClose(err);
      this.close();
    });
  }

  close() {
    this.view.dismiss();
  }

} 

这里是http操作:

const SERVER_URL: any = {
    getNormal: ConstantVariable.APIURL + 'index.php/tbl_note',
    getLimit: ConstantVariable.APIURL + 'limit.php',
};

@Injectable()
export class CrudHttpProvider {

    limitData: number = 10;
    datas: any = [];

    constructor(public http: Http) {
        this.datas = null;
    }

    get read() {
        return new Promise(resolve => {
            this.http.get(SERVER_URL.getNormal).map(res => res.json()).subscribe(data => {
                console.log(data.dataNotes);
                resolve(data.dataNotes);
            });
        });
    }



    save(item) {
        let headers: any = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }),
            options: any = new RequestOptions({ headers: headers });

        if (item.id) {
            return new Promise((resolve, reject) => {
                this.http.post(SERVER_URL.getNormal + '/' + item.id, item, options).map(res => res.json()).subscribe((data) => {
                    console.log(data);
                    resolve(data.dataNotes);
                }, (err) => {
                    reject(err);
                    console.log("error: " + err);
                });
            });
        }
        else {
            return new Promise(resolve => {
                this.http.post(SERVER_URL.getNormal, item, options)
                    .map(res => res.json())
                    .subscribe(data => {
                        // console.log(data);
                        resolve(data.dataNotes[0].id);
                    }, error => {
                        console.log("error " + error);
                    });
            });
        }
    }

最后是PHP文件:

<?php
    header('Access-Control-Allow-Origin: *');
    require_once('config.php');

    // get the HTTP method, path and body of the request
    $method = $_SERVER['REQUEST_METHOD'];
    $request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
    $input = json_decode(file_get_contents('php://input'),true);

    // retrieve the table and key from the path
    $table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
    $key = array_shift($request)+0;

    // escape the columns and values from the input object
    $columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input));
    $values = array_map(function ($value) use ($link) {
      if ($value===null) return null;
      return mysqli_real_escape_string($link,(string)$value);
    },array_values($input));

    // build the SET part of the SQL command
    $set = '';
    for ($i=0;$i<count($columns);$i++) {
      $set.=($i>0?',':'').'`'.$columns[$i].'`=';
      $set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
    }

    // create SQL based on HTTP method
    if ($method == "POST" AND $key != "") { $method = 'PUT'; }
    if ($method == "GET" AND $key != "") { $method = 'DELETE'; }
    switch ($method) {
      case 'GET':
        $sql = "select * from `$table`".($key?" WHERE id=$key":''); break;
      case 'PUT':
        $sql = "update `$table` set $set where id=$key"; break;
      case 'POST':
        $sql = "insert into `$table` set $set"; break;
      case 'DELETE':
        $sql = "delete from `$table` where id=$key"; break;
    }

    // excecute SQL statement
    $result = mysqli_query($link,$sql);

    // die if SQL statement failed
    if (!$result) {
      http_response_code(404);
      die(mysqli_error());
    }

    // print results, insert id or affected row count
    echo "{"status":"ok", "dataNotes":";

    if ($method == 'GET') {
        if (!$key) echo '[';
        for ($i=0;$i<mysqli_num_rows($result);$i++) {
            echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
          }

        if (!$key) echo ']';
    } elseif ($method == 'POST') {
        $set = '"id":"'.mysqli_insert_id($link).'"';
        for ($i=1;$i<count($columns);$i++) {
          $set.=($i>0?',':'').'"'.$columns[$i].'":';
          $set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
        }
        echo "[{".$set."}]";
    } elseif ($method == 'DELETE') {
        echo '[{"id":"'.$key.'"}]';
    } else {
      echo mysqli_affected_rows($link);
    }
    echo "}";

    // close mysql connection
    mysqli_close($link);
答案

问题可能在这里:

  edit(item) {
    let modal = this.modal.create('CrudHttpDetailPage', { data: item, action: 2 });
    modal.present();
    modal.onDidDismiss(data => {
      if (data) this.load(); // <---- seems this.load() is not executing
    });
  }

似乎this.load()之后没有执行modal.onDidDismiss:-检查模态是否关闭-检查data是否不为null / undefined-检查运行中的this.load(),没有if()语句,它是否运行?您也许可以在那里找到答案

  edit(item) {
    let modal = this.modal.create('CrudHttpDetailPage', { data: item, action: 2 });
    modal.present();
    modal.onDidDismiss(data => {
      console.log('Modal has dismissed!!');
      // if (data) this.load(); // comment for check
      this.load();
    });
  }
另一答案

我终于解决了这个问题。问题的原因在于,我有两个文件用于连接数据库,一个用于网站,另一个用于移动应用程序,看来我在移动应用程序中使用的那个文件已损坏,因此我删除了该文件并连接到旧文件,问题解决了

以上是关于离子v3在应用程序中进行制造和更新,以更新它在数据库中而不是在应用程序中正在更新的数据的主要内容,如果未能解决你的问题,请参考以下文章

更新 apollo 缓存而不调用 graphql 服务器(apollo v3.3)

在离子v1中添加新数据后,angularjs ng-repeat不会更新

离子地理定位 - 如何更新位置?

为啥图像名称未显示在表单字段中以进行更新?

d3.js - v3 和 v4 - 输入和更新差异

活字格企业Web应用生成器V3.0发布更新,支持插件管理和多人协作开发