I'm trying to move my Api calls to a service. Until now I've made api calls in every component that needed it, which also resulted to passing a lot of variables to other components and generally resulted in a lot of garbage in my code.
So, when my api calls were in my component, where I needed the objects that I requested, it was all fine - I've launched the HttpClient get method, and the page updated when the correct object was received.
Now, when I'm trying to move it to a service, it doesn't update - I'll explain it in my code.
Here's the method in my service:
getProjects(): any {
this.http.get<Project[]>('http://localhost:54639/api/tfs/projects').subscribe(data => {
console.log(data['value']);
return data['value'];
});
}
And here's the request to this method I'm making in my component:
ngOnInit(): void {
console.log("I'm in OnInit!");
this.projects = this.ApiConnection.getProjects();
console.log(this.projects);
}
So, here's the problem: my console first logs "I'm in OnInit!", then logs undefined - both from ngOnInit, and then it logs the correct data form getProjects() in my service.
I'm trying to somehow await this, but to be honest, I've got no idea how. I tried making a promise out of it, tried using await, map or .then(), but it doesn't seem to work, and google isn't helping much.
Edit: ugh, I do get it's asynchronous, I've even specified "how to await" in the title... Problem is, I've got no idea how to do it in TypeScript and with Angular4 HttpClient. The answers in the topic I've supposedly duplicated are regarding callbacks and premises, while I'm trying to await an observable....