Ionic 3 Uncaught(承诺):[object Object] [英] Ionic 3 Uncaught (in promise): [object Object]

查看:643
本文介绍了Ionic 3 Uncaught(承诺):[object Object]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Ionic 3和移动开发的新手。我正在尝试将MySQL数据库连接到我的Ionic应用程序和PHP Restful API。我用Postman测试了API并且工作得很好,为了在Ionic中实现它我做了以下操作,
我首先创建了一个名为Authservice的提供者:

I am new to Ionic 3 and mobile development. I am trying to connect a MySQL DB to my Ionic app and a PHP Restful API. I tested the API with Postman and it is working just fine, in order to implement it in Ionic I did the following, I first made a provider named Authservice:

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

let apiUrl = "http://localhost/api/"
   /*
    Generated class for the AuthServiceProvider provider. 

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

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

  postData(credentials, type) {
return new Promise((resolve, reject) => {
  let headers = new HttpHeaders();

  this.http.post(apiUrl + type, JSON.stringify(credentials), { headers:    headers })
    .subscribe(res => {
      resolve(res.json());
    }, (err) => {
      reject(err);
    });
   });

      }

     }

并注册页面:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { AuthServiceProvider } from '../../providers/auth-service/auth-  service';

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

 @IonicPage()
 @Component({
selector: 'page-signup',
templateUrl: 'signup.html',
})
export class SignupPage {
 responseData: any;
userData = {"username": "","password": "", "name": "","email": ""};
 constructor(public navCtrl: NavController, public authServiceProvider:   AuthServiceProvider) {
    }
   signUp() {
    this.authServiceProvider.postData(this.userData, "signup").then((result) =>{
     this.responseData = result;
     console.log(this.responseData);
      localStorage.setItem('userData', JSON.stringify(this.responseData));
      });
        }
       goToLogin() {
      this.navCtrl.pop();
           }
           }

执行此操作时,我得到了一个未知(在承诺中) ):[object Object]错误,可以在这里看到。

When running this I am getting an Uncaught (in promise): [object Object] error as can be seen here.

更新

我现在得到以下内容错误:

I am now getting the following error:

Object { headers: {…}, status: 404, statusText: "Not Found", url: "http://localhost/PHP-SLIM-RESTFUL/API/signup", ok: false, name: "HttpErrorResponse", message: "Http failure response for http://localhost/PHP-SLIM-RESTFUL/API/signup: 404 Not Found", error: "<html><head><title>404 Page Not Found</title><style>body{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}</style></head><body><h1>404 Page Not Found</h1><p>The page you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly. If all else fails, you can visit our home page at the link below.</p><a href=\"/PHP-Slim-Restful/api/\">Visit the Home Page</a></body></html>" } signup.ts:36:6


推荐答案

您可以使用Typescript的 async 让您的生活更轻松的方法

You can make use of Typescript's async methods to make your life easier

您的 postData 异步中的方法

AuthServiceProvider:

public async postData(credentials, type): Promise<any> {
    let headers = new HttpHeaders();
    await this.http.post(apiUrl + type, JSON.stringify(credentials), { headers: headers }).toPromise();
}

注册页面:

public async signUp(): void {
    try {
      // request successful
      this.responseData = await this.authServiceProvider.postData(this.userData, "signup");
      console.log(this.responseData);
      localStorage.setItem('userData', JSON.stringify(this.responseData));
    } 
    catch(e) {
      // some error occured, handle it here..
      console.log(e);
    }
}

不要忘记导入 toPromise 运算符> AuthServiceProvider

import 'rxjs/add/operator/toPromise';

这篇关于Ionic 3 Uncaught(承诺):[object Object]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆