【问题标题】:Ionic 3 Uncaught (in promise): [object Object]Ionic 3 Uncaught (in promise): [object Object]
【发布时间】:2018-08-26 01:33:39
【问题描述】:

我是 Ionic 3 和移动开发的新手。我正在尝试将 MySQL DB 连接到我的 Ionic 应用程序和 PHP Restful API。我用 Postman 测试了 API,它工作得很好,为了在 Ionic 中实现它,我做了以下工作, 我首先创建了一个名为 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();
           }
           }

运行此程序时,我收到 Uncaught (in promise): [object Object] 错误,可能是 seen here.


更新

我现在收到以下错误:

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

【问题讨论】:

  • 请以文本形式分享您的错误信息,而不是图片
  • @NicoHaase Uncaught (in promis): [object Object]

标签: php angular rest api ionic-framework


【解决方案1】:

尝试在app.module.ts中导入HttpModule;

{import HttpModule } from '@angular/http'

然后将 HttpModule 添加到导入中;

imports : [BrowserModule, HttpModule, IonicModule.forRoot(MyApp) ]

【讨论】:

    【解决方案2】:
    postData(credentials, type) {
      let headers = new HttpHeaders();    
      return this.http.post(apiUrl + type, JSON.stringify(credentials), { headers:    headers });
    }
    

    这将在注册页面上返回 observable,只需订阅它。

    【讨论】:

      【解决方案3】:

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

      你的 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);
          }
      }
      

      不要忘记在AuthServiceProvider 中导入toPromise 运算符

      import 'rxjs/add/operator/toPromise';
      

      【讨论】:

      • @Imdad Ali 谢谢你们的回答我做了你们告诉我的事情,表格没有提交到数据库,我检查了控制台并收到了这个错误 Object { headers: {...}, status :0,statusText:“未知错误”,url:null,ok:false,名称:“HttpErrorResponse”,消息:“(未知url)的Http失败响应:0未知错误”,错误:错误}signup.ts:36 :6 i.imgur.com/Afbx5DL.png
      • 即使我面临同样的问题/错误.. 你有什么解决办法吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-25
      • 2019-07-05
      • 2018-03-01
      • 2018-09-02
      • 2022-12-02
      相关资源
      最近更新 更多