0

I'm having trouble making a function that returns the data "array" that I want to consume using a Promise. The tech stack that I'm using is Angular, Typescript and Express.js. I can get the data to return inside of the getData() function however, the data is not passed on in the return statement, I just get an empty array in ngOnInit();

getData Function:

public async getData(user: any): Promise<any> {

        this._url = 'http://localhost:5000/account/data';

        const data = this._http.post<any>(this._url, user).toPromise();

        return data

 
    }

ngOnInit:

ngOnInit(): void {

    this._account.getData(this.login)
    .then((data: any) => {
      console.log(data)
    });

  }

result = [ ]; 
R. Richards
  • 24,603
  • 10
  • 64
  • 64
MrHam92
  • 1
  • 1

1 Answers1

0

Try this (just to add await to yout http call):

public async getData(user: any): Promise {

    this._url = 'http://localhost:5000/account/data';

    const data = await this._http.post<any>(this._url, user).toPromise();

    return data
}

ngOnInit(): void {
   this._account.getData(this.login)
   .then((data: any) => {
      console.log(data)
   });
}

EXTRA: A better way to work with angular http Module, is the OBSERVABLE way:

import { Observable } from 'rxjs';


public getData(user: any): Observable<any> {
    this._url = 'http://localhost:5000/account/data';
    return this._http.post<any>(this._url, user);
}

ngOnInit(): void {
   this._account.getData(this.login)
   .subscribe((data: any) => {
      console.log(data)
   });
}