运行时错误:this.userprovider.userSignup(...)。subscribe不是Ionic中的函数

时间:2018-06-29 06:18:11

标签: angular mongodb ionic-framework

下面是signup.ts

我想在MongoDB中插入数据。 我收到类似

的错误
  

this.userprovider.userSignup(...)。subscribe不是函数。

请帮助我解决错误

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ViewController } from 'ionic- 
angular';
import { UserProvider } from '../../providers/user/user';

@IonicPage()
@Component({
  selector: 'page-signup',
  templateUrl: 'signup.html',
})

export class SignupPage {

  private registerUrl = 'http://localhost:8080/signup';
  username: string;
  email: string;
  password: string;
  repassword: string;

  constructor(public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController, public userprovider: UserProvider) {
  }

  signup(): void {

    let review = {
      username: this.username,
      email: this.email,
      password: this.password,
      repassword: this.repassword
    };
    console.log(review);

    this.userprovider.userSignup(review).subscribe(

      res => {
        console.log(res);
      },
      error => {
        //this.loading = false;
        console.log(error);
      });
  }
}

下面是provider / user.ts 此文件是提供程序文件。我曾经在这里订阅。但这会带来问题..那么解决方案

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/catch';
import { BehaviorSubject } from 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class UserProvider {
  data: any;
  private registerUrl = 'http://localhost:8080/signup';

  constructor(public http: Http) {
    this.data = null;
  }

  userSignup(review): any {

    return this.http.post(this.registerUrl, review)
      .subscribe(res => {
        console.log(res.json());
      });
  }
}

如您所见,我已经尝试过用我的方式解决该错误。也许有人知道我该如何解决?

2 个答案:

答案 0 :(得分:0)

只需返回服务的响应即可。由于您正在从组件中订阅可观察对象,因此无需从服务中订阅它。

userSignup(review):Observable<any>{

  return this.http.post(this.registerUrl, review);
}

答案 1 :(得分:0)

这里有两个问题,

(i)您只能订阅一个可观察对象,将您的返回类型更改为

userSignup(review):Observable<any>

(ii)您应该仅在组件内使用订阅,而不是在service方法内使用。因此,将您的方法更改为

userSignup(review):Observable<any>{
  return this.http.post(this.registerUrl, review);
}