Reputation: 31
I'm trying to get data from an API with a service. And then log it from inside a module which is later going to show it in a list. The variable shows up in the console.log in the service but not when I try to log it in de module
This same set up i've made before with ionic, I figured angular would work the same but that isn't the case here. I've already expanded the .subscribe function with error handling but no errors show up. I just don't know where to look.
api.service.ts
getPlacesData(): any {
let result = this.http.get(`${this.apiUrl}/places`, this.httpOptions).pipe(
map(response => {
console.log(response['data']);
response['data'];
})
);
return result;
}
}
test-dashboard.component.ts
constructor(private breakpointObserver: BreakpointObserver, private apiService: ApiService) {}
getPlacesData() {
this.apiService.getPlacesData().subscribe(
(placesData: Observable<any>) => {
console.log(placesData);
this.placesData = placesData;
console.log(this.placesData);
},
(error: string) => {
console.log('Received an errror: ' + error);
}
);
}
ngOnInit() {
this.getPlacesData();
}
}
I expect the second and third console.log to have the same output as the first one, but the output from those is "undefined" instead of:
(15) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
Upvotes: 2
Views: 816
Reputation: 9124
The issue is that you are trying to return a value synchronously. Angular https requests are asynch. Please treat them as such. Your function should return the Observable. Use async pipe in your html template to access the data after.
getPlacesData(): Observable<Places[]> {
return this.http.get<Places[]>(`${this.apiUrl}/places`, this.httpOptions).pipe(
map(response => response['data']),
);
}
}
Upvotes: 2
Reputation: 648
Try something like this
getPlacesData(): any {
return this.apiService.get(this.terminateSurveyUrl, terminateSurveyReqObj)
.pipe(
map((response:any) => {
console.log('response',response);
return response.data;
}),
)
}
Hope it helps!
Upvotes: 1
Reputation: 19843
You have to return data in your map
function
map(response => {
console.log(response['data']);
return response['data'];
})
or
map(response => response['data'])
Also in your subscription type of value is not Observable any more in your case it will be Array
(placesData: Array<any>)
Upvotes: 0