【问题标题】:Ionic 3 Angular 5 post data HttpClientIonic 3 Angular 5 发布数据 HttpClient
【发布时间】:2018-04-20 17:57:14
【问题描述】:

我正在尝试在本地网络服务中发布数据,但我无法在企业中进行:P 无论如何,这是我尝试编写的代码:

在提供程序中 (src/providers/team-data/team-data.ts)

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { map, catchError } from 'rxjs/operators';
import 'rxjs/add/operator/map';

@Injectable()
export class TeamDataProvider {

  apiUrlGet="http://localhost/MyWebService/api/getteams.php";
  apiUrlAdd="http://localhost/MyWebService/api/createteam.php";

  constructor(public http: HttpClient) {
    console.log('Hello TeamDataProvider Provider');
  }

  getTeams(): Observable<any[]> {    
    return this.http.get(this.apiUrlGet).pipe(
      map(this.extractData),
      catchError(this.handleError)
    );    
  }

  private extractData(res: Response) {
    let body = res;
    return body || {};
  }

  private handleError (error: Response | any) {
    let errMsg: string;
    if (error instanceof Response) {
      const err = error || '';
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

  getRemoteData(){
    this.http.get(this.apiUrlGet).map(res => res).subscribe(data => {
    console.log(data);
    });
  }

  addTeam(data) {
    return new Promise((resolve, reject) => {
      this.http.post(this.apiUrlAdd, JSON.stringify(data))
        .subscribe(res => {
          resolve(res);
        }, (err) => {
          reject(err);
        });
    });
  }

}

在 addteam.ts 中

import { TeamDataProvider } from './../../providers/team-data/team-data';
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

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

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

  teams = {
      name: '',
      member: ''
  }

  constructor(public navCtrl: NavController, public navParams: NavParams, public teamDataProvider: TeamDataProvider) {
  }

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

  saveTeam() {
    this.teamDataProvider.addTeam(this.teams).then((result) => {
      console.log(result);
    }, (err) => {
      console.log(err);
    });
  }

}

并在 addteam.html 中

<!--
  Generated template for the AddteamPage page.

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

  <ion-navbar>
      <button ion-button menuToggle>
          <ion-icon name="menu"></ion-icon>
        </button>
    <ion-title>addteam</ion-title>
  </ion-navbar>

</ion-header>


<ion-content padding>
  <h2>Add User</h2>
  <form (ngSubmit)="saveTeam()">
    <ion-item>
      <ion-label>TeamName</ion-label>
      <ion-input type="text" [(ngModel)]="teams.name" name="name"></ion-input>
    </ion-item>
    <ion-item>
      <ion-label>TeamMember</ion-label>
      <ion-input type="text" [(ngModel)]="teams.member" name="member"></ion-input>
    </ion-item> 
    <button ion-button type="submit" block>Add Team</button>
  </form>

</ion-content>

当我启动应用程序并填写字段后,我按下按钮将字段添加到我的数据库中,在控制台中出现此错误:

HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: "OK", url: "http://localhost/MyWebService/api/createteam.php", ok: false, …}
error
:
error
:
SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.onLoad (http://localhost:8100/build/vendor.js:73072:51) at t.invokeTask (http://localhost:8100/build/polyfills.js:3:15660) at Object.onInvokeTask (http://localhost:8100/build/vendor.js:5114:33) at t.invokeTask (http://localhost:8100/build/polyfills.js:3:15581) at r.runTask (http://localhost:8100/build/polyfills.js:3:10834) at e.invokeTask [as invoke] (http://localhost:8100/build/polyfills.js:3:16794) at p (http://localhost:8100/build/polyfills.js:2:27648) at XMLHttpRequest.v (http://localhost:8100/build/polyfills.js:2:27893)
message
:
"Unexpected token < in JSON at position 0"
stack
:
"SyntaxError: Unexpected token < in JSON at position 0↵    at JSON.parse (<anonymous>)↵    at XMLHttpRequest.onLoad (http://localhost:8100/build/vendor.js:73072:51)↵    at t.invokeTask (http://localhost:8100/build/polyfills.js:3:15660)↵    at Object.onInvokeTask (http://localhost:8100/build/vendor.js:5114:33)↵   at t.invokeTask (http://localhost:8100/build/polyfills.js:3:15581)↵    at r.runTask (http://localhost:8100/build/polyfills.js:3:10834)↵    at e.invokeTask [as invoke] (http://localhost:8100/build/polyfills.js:3:16794)↵    at p (http://localhost:8100/build/polyfills.js:2:27648)↵    at XMLHttpRequest.v (http://localhost:8100/build/polyfills.js:2:27893)"
__proto__
:
Error
text
:
"<br />↵<b>Notice</b>:  Undefined index: name in <b>/Applications/XAMPP/xamppfiles/htdocs/MyWebService/api/createteam.php</b> on line <b>15</b><br />↵<br />↵<b>Notice</b>:  Undefined index: member in <b>/Applications/XAMPP/xamppfiles/htdocs/MyWebService/api/createteam.php</b> on line <b>16</b><br />↵{"error":true,"message":"Could not add team"}"
__proto__
:
Object
headers
:
HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message
:
"Http failure during parsing for http://localhost/MyWebService/api/createteam.php"
name
:
"HttpErrorResponse"
ok
:
false
status
:
200
statusText
:
"OK"
url
:
"http://localhost/MyWebService/api/createteam.php"
__proto__
:
HttpResponseBase

当我尝试向 Postman 发出发帖请求时, 将正确的 url 作为 POST 插入, 并插入正文 -> 表单数据, key:name和member,填写并发送请求后,在body -> Pretty中出现消息“{”error“:false”,message“:”团队添加成功“}”,字段实际添加在数据库。

我做错了什么?我该怎么做才能让它工作? 谢谢。

【问题讨论】:

    标签: angular web-services post ionic-framework httpclient


    【解决方案1】:

    几天前我正在为类似的问题而苦苦挣扎。最后,我为 FormData 转换了数据对象。保存 FormData 而不是 json 解决了我的问题。

    addTeam(data) {
        return new Promise((resolve, reject) => {
          this.http.post(this.apiUrlAdd, this.getFormData(data))
            .subscribe(res => {
              resolve(res);
            }, (err) => {
              reject(err);
            });
        });
      }
            getFormData(object) {
                const formData = new FormData();
                Object.keys(object).forEach(key => formData.append(key, object[key]));
                return formData;
            }
    

    【讨论】:

    • 为什么要使用promise?只是好奇。我也在别的地方看到过。
    • Promise 是当今 JavaScript 异步处理的标准。您并使用resolve 和reject 来识别流程输出。还有一点很重要,你可以用 then 来实现这些承诺。
    • 知道了,谢谢。我们以前使用地图,然后再订阅它。
    猜你喜欢
    • 2018-07-05
    • 1970-01-01
    • 2018-02-25
    • 2019-03-07
    • 1970-01-01
    • 2018-07-24
    • 2017-12-29
    • 2020-05-04
    • 1970-01-01
    相关资源
    最近更新 更多