函数返回无效(离子性)

时间:2019-07-09 12:30:46

标签: ionic-framework ionic2 ionic3 ionic4 ionic-native

im tryng从此http.get

获取响应
getChatId(emailTo): any {
    var email = emailTo

    const httpOptions = {
      headers: new HttpHeaders({
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Token': this.token_value
      })
    };

    this.httpClient.get("https://xxxx=" + email, httpOptions)
      .subscribe(data => {
        console.log(data['_body']);
        return data
      }, error => {
        console.log(error);
        return error
      });
  }

在我的构造函数中

this.getChatId(this.emailTo).then((date) => {

      var docRef = firebase.firestore().collection("xxx").doc(date.response);

      docRef.onSnapshot((doc) => {
        this.document = doc.data()

        let chats_message = [];
        for (let k in this.document.messages) {
          chats_message.push(this.document.messages[k]);
        }
        chats_message.sort(function (a, b) { return a.id - b.id; })
        this.messages_chat = chats_message;
        this.content.scrollToBottom(300);//300ms animation speed

        console.log("Array", this.messages_chat);
      })
    });

但是它给了我这个错误:

  

vendor.js:1823错误错误:未捕获(承诺):TypeError:无法   读取未定义TypeError的属性“订阅”:无法读取属性   未定义的“订阅”

2 个答案:

答案 0 :(得分:0)

在请求时,subclient不是httpclient中的函数。请按照以下代码

import { Component } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
 
@IonicPage()
@Component({
  selector: 'page-sample',
  templateUrl: 'sample.html',
})
export class SamplePage {
  sampleDatas: Observable<any>;
 
  constructor(public navCtrl: NavController, public httpClient: HttpClient) { 
    this.films = this.httpClient.get('https://swapi.co/api/films');
    this.sampleDatas
    .subscribe(data => {
      console.log('my data: ', data);
    })
  }

答案 1 :(得分:0)

您应该将其功能重写为与httpclient交互的Observable。最好是在像ChatService这样的服务文件中。您可以使用接收或发送的模型或任何类型来设计http请求。

export class ChatService {

  constructor(private http: HttpClient) {}

  getChatId(emailTo: string): Observable<any> {
    return this.httpClient.get<any>("https://xxxx=/" + email);
  }

}

在注入了构造函数的服务的页面上调用http请求。

constructor(private chatService: ChatService) {}

getChatId() {
  this.chatService.getChatId(this.emailTo).subscribe(
    result => {
      // do something with result
    },
    error => {
      // do something with error
    }
  );
}

编辑

如果您使用模型来传递和接收http请求中的数据,则可以将它们定义为类型。 https://blog.angular-university.io/angular-http/

import { User } from '../models/user';

export class ChatService {

  constructor(private http: HttpClient) {}

  getChatId(emailTo: string): Observable<User> {
    return this.httpClient.get<User>("https://xxxx=/" + email);
  }

}