Search code examples
ionic-frameworkionic2ionic3ionic4ionic-native

Return from function doesn’t work (ionic)


im tryng to get the response from this 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 inside my constructor

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

but it give me this error:

vendor.js:1823 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'subscribe' of undefined TypeError: Cannot read property 'subscribe' of undefined


Solution

  • Subscribe is not a function in httpclient while the request. please follow the below code

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