Reputation:
Most of this stuff in Angular 5 with typescript and rxjs with observables is pretty similar to angular 2, 4 - yet I seem to be having trouble with understanding WHY my component code is not showing data.
Here is my code
model:
export class arsCodes {
iD: number;
aRSCode: string;
aRSDescription: string;
class: string;
victimFlag: string;
startDate: string;
endDate: string;
createdByUserID: string;
createdOnDateTime: string;
modifiedByUserID: string;
modifiedOnDateTime: string;
}
Working Service
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
getArsCodesApi(search: arsCodes) {
return this.http.post(this.serviceUrl, JSON.stringify(search), httpOptions)
.map((response: Response) => {
response;
console.log(response) // WORKS
})
}
The "response" in console.log above returns { Status: "success", Message: "", data: Array(16) }
Then
data: Array(16)
>0: {ID: 4443, ..... }
//etc..
However, it is in my call from the Component file in the subscribe that it is undefined
arsCode: ArsCode[];
this.arsSevice.getArsCodesApi(this.model).subscribe(
result => {
//this.arsCode = result
console.log(result);
},
error => {
console.log(error);
}
)
What do I need to do in my component to retrieve the data?
Upvotes: 2
Views: 2832
Reputation: 2049
The problem is that you are not returning anything in the .map() function of your service (which by using HttpClient is not required)
But anyways, you have to return like this:
return this.http.post(this.serviceUrl, JSON.stringify(search), httpOptions)
.map((response: Response) => {
console.log(response);
return response;
});
Upvotes: 3
Reputation: 177
You're returning the map function. Include this code in your http petition to return data:
return this.http.post(this.serviceUrl, JSON.stringify(search), httpOptions)
.map(this.extractData)
.catch(this.handleError);
Extraction from plain data are a simple return:
private extractData(res: Response): Observable<any> {
return res|| { };
}
Use return res.json for JSON data. You also can use this for error control:
private handleError(error: any){
return Observable.throw("Data unavailable or incorrect url");
}
Upvotes: 1