Suppose there is a scenario where a service retrieves a list of properties:
export class PropertyService {
private properties: any;
constructor(@Inject(Http) http) {
this.http.get('/properties.json')
.map((res:Response) => res.json())
.subscribe(
data => this.properties = data
);
}
getProperty(property: string) {
this.properties[property];
}
}
The issue arises when getProperty
is called before properties
are fully loaded.
How can we ensure that getProperty
waits for the array to be populated through subscription, without returning a subscription to the components?
UPDATE:
I attempted the method suggested by paulpdaniels using pluck
, but faced challenges quickly.
Essentially, I have a PropertyService that provides a HOST
.
There is also an ApiService leveraging this host for another AJAX call to fetch data.
export class PropertyService {
private properties: any;
constructor(@Inject(Http) http) {
this.properties = http.get('/properties.json')
.map((res:Response) => res.json()).cache(1);
}
getProperty(property: string) {
this.properties.pluck(property);
}
}
export class ApiService {
private http: Http;
private host: string;
constructor(@Inject(Http) http, @Inject(PropertyService) propertyService) {
this.http = http;
this.host = propertyServiceService.getProperty("API.URL"); //Subscription occurs here
}
getData(): any {
//Need to subscribe to host and once available, use it to make an AJAX call
//that returns another Observable for the component
}
}
Any suggestions on how to achieve this?