Ionic 2 TypeError: this.http.post is not a functio

2019-09-07 00:48发布

问题:

Hi i'm trying to make a signup page in ionic 2 that post username, email and password to the api that i use. But i get this error TypeError: this.http.post is not a function. I've already search about this problem and try but it doesn't work for me.

Here's my signup.js:

import {Injectable, Inject} from 'angular2/core';
import {Page, NavController} from 'ionic-angular';
import {TabsPage} from '../tabs/tabs';
import {UserData} from '../../providers/user-data';
import {Http, Headers, RequestOptions} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/Rx';

@Page({
  templateUrl: 'build/pages/signup/signup.html'
})
@Injectable()
export class SignupPage {
  static get parameters() {
    return [[Http], [NavController], [UserData]];
  }

  constructor(nav, userData, http) {
    this.nav = nav;
    this.userData = userData;
    this.http = http;

    this.signup = {};
    this.submitted = false;
  }

  onSignup(form) {
    let body = JSON.stringify(form.value);
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    headers.append('Accept', 'application/json');
    let options = new RequestOptions({ headers: headers });
    this.http.post('http://localhost:8000/api/v1/auth/register', body, options)
        .map(res => res.json())
        .subscribe(
            data => this.success = data
        )
        .catch(this.handleError);
  }

  handleError(error) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}

please help!

回答1:

I think that it's because the order of providers you use at the level of the parameters getter and the constructor:

static get parameters() {
  return [[Http], [NavController], [UserData]]; // <-----
}

constructor(nav, userData, http) { // <-----
}

You need to define the same order at both levels (and also square brackets the right way), as described below:

static get parameters() {
  return [[NavController, UserData, Http]]; // <-----
}

constructor(nav, userData, http) {
}