I am facing an issue with a service (referred to as MySharedService
) that is utilized by multiple components. Within MySharedService
, I invoke another service responsible for making API calls. The JavaScript object in MySharedService
is only assigned after the GET
call is completed.
The challenge lies in my components relying on this JavaScript object to configure their values within their constructors. How can I ensure that their values are set when the JavaScript object might still be undefined due to the incomplete API call? Here's an example:
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 occurs here if myData has not been populated yet.
this.name = this.mySharedService.myData.name;
}
}
The dilemma arises within my components when trying to access data from the myData
object before it is fully populated (the console.log()
eventually displays the data after a short delay). What would be the best approach to retrieve these values? I aim to make a single call to the REST service, save the object within MySharedService
, and allow all components to utilize that object.