Return 来自函数不起作用(离子)

Return from function doesn’t work (ionic)

我正在尝试从这个 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 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'subscribe' of undefined TypeError: Cannot read property 'subscribe' of undefined

请求时订阅不是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);
    })
  }

您应该将函数重写为 Observable 以与 httpclient 交互。最好在服务文件中,例如 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);
  }

}