I have a service (lets call it MySharedService
) which multiple components use. Inside MySharedService
, I call another service that makes API calls. MySharedService
holds a JavaScript object that is assigned after my GET
call.
My problem is that my components rely on that JavaScript object to set their values in their constructors. How can I set their values when that JavaScript might be undefined because the API call has not completed yet? Here's a sample:
ApiService
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
/* Other imports */
@Injectable()
export class ApiService {
constructor(private http: HttpClient) { }
getTestData(): Observable<MyDataInterface> {
const API_URL = 'some_url_here';
return this.http.get<MyDataInterface>(API_URL, { observe: 'response' });
}
}
MySharedService
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
/* Other imports */
@Injectable()
export class MySharedService {
myData: MyDataInterface;
constructor(private apiServie: ApiService) {
this.apiService.getTestData().subscribe((response) => {
this.myData = { ...response.body };
console.log(this.myData);
});
}
}
TestComponent
import { Component, OnInit } from '@angular/core';
import { MySharedService } from '../../../services/myshared.service';
/* Other imports */
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
name: string;
/* Other variables here. */
constructor(private mySharedService: MySharedService) {
// Error here because myData has not been populated, yet.
this.name = this.mySharedService.myData.name;
}
}
So the problem happens inside my components when I try to access data from the myData
object because it hasn't been populated, yet (the console.log()
does eventually print the data out after a couple of seconds). How am I supposed to go about getting the values? I only want to call the rest service once and save the object inside MySharedService
then have all my components use that object.