I'm trying to return data from a service using subscribe method.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class DevRequestService {
constructor(private http: HttpClient){}
getListOfAgencies() {
return this.http.get('https://example.com/api/agency').subscribe(data => {
return data;
});
}
}
Component:
ngOnInit(): void {
console.log(this.devRequestService.getListOfAgencies());
}
Below is the output that I'm getting in console.log instead of returning the object with the values:
Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null, …}
You should subscribe for the data and assign it to a variable in component like below:
ngOnInit(): void {
this.devRequestService.getListOfAgencies().subscribe((data) => {
this.agencies = data;
})
};
I would do this in your .ts: private data$: Observable;
ngOnInit(): void {
this.data$ = this.devRequestService.getListOfAgencies();
}
and in your .html template, this:
<div> {{ data$ | async }} </div>
in order to get the value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With