Ionic 3-如何将id参数传递到“ http delete”功能中并仅删除特定用户?

时间:2018-10-31 13:40:58

标签: php angular ionic-framework ionic3

我正在尝试从数据库服务器中删除数据。如何将特定的用户ID传递到HTTP删除请求中,以便仅删除一个用户而不删除所有用户数据?我正在使用核心PHP DB和Ionic 3。

下面是我的代码:

Home.html

<ion-content padding>
  <ion-list>

    <ion-item *ngFor="let user of (users | async)?.users" (click)="viewItem(user._id)">

      <ion-avatar item-left>
        <img src="assets/imgs/logo.png">
      </ion-avatar>
      <h1>{{user.id}}</h1>
      <h2>{{user.name}}</h2>
      <p>{{user.bday}}</p>

      <ion-icon name='trash' (click)="deleteitem(user._id)" item-end color="secondary"></ion-icon>

    </ion-item>

  </ion-list>
</ion-content>

home.ts

deleteitem(id: number){
    let users = {
            userId: id
        };
    this.restProvider.deleteItem(users)
    .subscribe(data => {
                this.items = data;
            }, err => {
                console.error(err);
            });
  }

provider.ts

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from  'rxjs/Observable';
import { Headers, RequestOptions } from '@angular/http';
.
.
baseUrl = 'http://url/project_folder';
.
.
deleteItem(user) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');

    return new Promise((resolve, reject) => {
      this.http.delete(this.baseUrl+'/delete_info.php'+'/?id=' + '{user.userId}')
        .subscribe(res => {
          resolve(res);
        }, (err) => {
          reject(err);
        });
    });
  }

delete.php

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$id=$_GET['id'];
        $servername = "servername";
        $username = "username";
        $password = "password";
        $database = "database";
        // Create connection

        $conn = new mysqli($servername, $username, $password, $database);

        // Check connection
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }

  $sql="delete from tbl_userinfo where id=$id";

  if ($conn->query($sql))
  {
      echo "delete data";
  }
  else
  {
      echo "Try again";
  }
?>

如果我这样输入:

http://url/project_folder/delete.php/?id=6

当我单击“删除”按钮时,显示如下错误:

core.js:1449 ERROR Error: Uncaught (in promise): [object Object]
at c (polyfills.js:3)
at polyfills.js:3
at SafeSubscriber._error (rest.ts:56)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:242)
at SafeSubscriber.error (Subscriber.js:201)
at Subscriber._error (Subscriber.js:132)
at Subscriber.error (Subscriber.js:106)
at MapSubscriber.Subscriber._error (Subscriber.js:132)
at MapSubscriber.Subscriber.error (Subscriber.js:106)
at FilterSubscriber.Subscriber._error (Subscriber.js:132)

网络响应:

http://url/project_folder/delete_info.php/?id={user.userId}

1 个答案:

答案 0 :(得分:1)

  1. 附加点击图标不是一个好主意
  2. provider.ts:... id ='+'{user.userId}'应该是... id ='+ user.userId。
  3. provider.ts:如果要返回Promise,应返回this.http.delete()。toPromise(),并且必须使用“ then”而不是home.ts订阅。
  4. provider.ts:如果您不想返回承诺,请返回this.http.delete()可以,然后在home.ts上使用
  5. php必须返回json数据。

以下示例:

<ion-button (click)="deleteitem(user)">
    <ion-icon name='trash' slot="icon-only"></ion-icon>
</ion-button>
function deleteitem(user) {
    this.restProvider.deleteitem(user._id).subscribe(data => {
                for(let i = 0, l = this.users.length; i < l; i++)
                    if (this.users[i]._id == user._id)
                        this.users.splice(i, 1);
            }, err => {
                console.error(err);
            });
}
function deleteitem(userId) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.delete(`${this.baseUrl}/delete_info.php?id=${userId}`);
}