Function that receives from another function an array coming from the backend via http request

Asked

Viewed 25 times

0

I have a function that I must pass to another function an id, which must perform a query in the backend and return me an array, I need to return to the initial function this listing, but when I give console.log(this.listaAtributos) i get undefined.

My main function:

getIdTipoVariacao(variacao: string, index: number) {

    this.listaAtributos = this.listaValoresAtributo(this.idTipoVariacao);
    console.log(this.listaAtributos);

}

My function responsible for searching the backend and returning a listing to the other function:

listaValoresAtributo(id: number):any {
    this.tipoProdutoService.listaValoresAtributo(id)
    .subscribe((res) => {

        return res.body.valores_atributos

        ,(err: HttpErrorResponse) => {

          if (err.status == 401) {
            this.authService.Logout();
          }

          return null
        }
      }
    )
  }

But I believe that the this.listaAtributos is not receiving the return of the request, because in my template I have a *ngFor which shows the contents of the variable this.listaAtributos and nothing is shown, and console.log() i get undefined.

@Edit:

I tried in the first function to subscribe to the second function observable return pro so:

    this.listaValoresAtributo(this.idTipoVariacao).subscribe((res) => {
      this.listaValoresAtributo = res;
    })

In the second function:

 listaValoresAtributo(id: number): Observable<any>{
 this.tipoProdutoService.listaValoresAtributo(id)
      .subscribe((res) => {

        return res.body.valores_atributos

        ...

But I get:

A Function Whose declared type is neither 'void' nor 'any' must Return a value.

  • you have to return the observable and do logica in the other function

  • I tried it in the first function: this.listValoresAtributo(this.idTipoVariation). subscribe(res) => { this.listValoresAtribute = res; }) E on the second: listValoresAtribute(id: number): Observable<any>{ ."

  • Edits the question I couldn’t understand with the comment

  • @Eduardo ready

  • missed a re-turn on Monday

  • return the observable without the subscribe

  • The Return needs to be inside the res() of the second function because it is where I have access to the return coming from the backend... I don’t know how to pass this return from inside the res() to the other function

  • This second function will be called by other 2 functions to copulate different listings, so I can’t do the logic within this res(), it has to be within the first function

  • just give subscribe every time calling the second function

  • very broad for me, but thank you

Show 5 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.