I am fairly new to Angular 2 and the idea of Observables. However, what I am trying to accomplish should be quite simple for experienced experts :)
Here's the situation: I have a component where I have subscribed to an observable coming from a service. In order to test my components, I have been using data arrays. Now that I'm done testing, I want to connect real API calls to my service. The issue arises when I try to manipulate the data received from the server before returning it to the component. This manipulation causes an error saying "cannot read property 'subscribe' of null."
This error occurs because in my service's observable, I send an API request using the HTTP.get method and the code doesn't wait for the response to finish. Although I do receive the result from the server, it comes after the error in the console.
Could someone please provide guidance on how to make an HTTP call, manipulate its data, and then send it to the subscribed component?
Below is the code snippet from my component:
getSearchResults(keyword, parentId?, subCatId?) {
this.subscriptionResults = this.catalogService.getSearchResults(keyword, parentId, subCatId)
.subscribe(
data => {
// Manipulate the received data here
if ( this.debugMode ) {
console.log('RESULTS: ', data);
}
},
error => this.errorMessage = <any>error
);
}
And here is my service code:
// Get data from server
getDataFromServer(URL: string): Observable<any> {
return this.http.get(URL).flatMap(this.extractData).catch(this.handleError);
}
getSearchResults(keyword: string, parentCatId?:number, subCatId?:number): Observable<any> {
let URL = this.API_URL + '/search?categoryId=' + subCatId + '&format=json';
// Make API Call
let request = this.getDataFromServer(URL);
request.subscribe(
() => {
// Modify the result data here before sending it back
},
error => { console.log('ERROR: ', <any>error); }
);
I need to manipulate the response data before returning it. How can I achieve this?
-- EDIT -- If I return a BehaviorSubject:
return new BehaviorSubject<any>(request.subscribe(
res => { return this.processResultData(res, layoutType, keyword, parentCatId, subCatId); },
err => { console.log('RETURN ERROR: ', <any>err); }
));
Instead of receiving the subscription object in my component, I actually need the data inside the subscription.