Angular: persist get return in function/variable

Asked

Viewed 336 times

0

booksList: Book[];

listById(id: number): Book{
        this.http.get<Book>(`${url}/list/id=${id}`)
        .subscribe((response)=> {
            this.book = response;
            console.log(this.book); //aqui existe o livro
            return this.book; //acho que não está servindo para nada
        });
        console.log(this.book); //aqui não existe
        return this.book; //acho que não está servindo para nada
    }

want to persist the return of this information in this.book to use in other functions, for example:

selectedBook() {
    let myBook = listById(1); (deve me retornar o objeto livro de id 1);
    this.booksList.push(this.book);
    console.log(booksList); //tem que existir o livro 1
}

However I can’t, as I commented in the code the variable always appears as Undefined, how to make the subscribe content persist outside of it?

I appreciate any help.

  • You have to return the observable and subscribe in your other way. You cannot return the direct book because the http call is asynchronous.

1 answer

4


Hello

Try to do the following:

listById(id: number): Book{
      return this.http.get<Book>(`${url}/list/id=${id}`)
}

In this function, the library is probably being used Http of the Angular itself, which returns an Observable. Service calls are usually (if not all) made asynchronously. So when you call using subscribe, it is "listening"/ waiting for the return of the service to then persist the value in the attribute that you need.

And in your other role:

async selectedBook() {
    let myBook = await listById(1).toPromise(); 
    this.booksList.push(this.book);
    console.log(booksList);
}

Use async / await to handle asynchronous requests more succinctly and objectively. the .toPromysis is to convert the observable into a Promise, in the case of the use of the async/await.

  • That’s exactly what it was, thank you very much !

  • You’re welcome, I’m glad it worked!

Browser other questions tagged

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