I've been exploring how to retrieve data from an Observable object, and after some research, I've come across two main solutions. One is using subscribe (which isn't working for me or perhaps I'm using it incorrectly), and the other is map, which no longer exists. Just to clarify, I am using Nest.js.
My objective here is to directly return the variable `this.followers` populated with the response data.
Below is my code:
import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
import { GithubFollower } from './../../../../shared/github.models'
@Injectable()
export class GithubService {
private followers: GithubFollower[]
constructor(private httpService: HttpService) {}
getFollowers(id: string): GithubFollower[] {
this.httpService.get<GithubFollower[]>(`https://api.github.com/users/${id}/followers`)
.subscribe(data => {
this.followers = data.data // this.followers = my data
console.log(this.followers); // print my data
});
console.log("here", this.followers); // print "here undefined"
return this.followers; // this.followers = []
}
}
How can I extract data from an Observable?