Angular: persist return of get in function / variable

-2
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
    }

I want to persist the return of this information in this.book to use in other functions, such as:

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 not, as I mentioned in the code, the variable always appears as undefined, how do the subscribe contents persist outside of it?

Thanks for any help.

    
asked by anonymous 27.12.2018 / 14:39

1 answer

1

Hello

Try to do the following:

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

In this function, the Http library of the Angular itself is probably being used, which returns an Observable. Service calls usually (if not all) are made asynchronously. So when you call using subscribe , it "listens" / waiting for the service to return, so that the value persists 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 .toPromise is to convert the observable into a promise, in the case of async / await .

    
27.12.2018 / 16:53