Reputation: 4502
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, …}
Upvotes: 4
Views: 26328
Reputation: 3409
I also had this problem where I was not getting a response, but rather a subscriber instance. It turned out the server code was not returning a JSON parsable response. Seemed like a silent error, not sure why. But when I fixed the server code to return an object, I got the response.
Upvotes: 0
Reputation: 21
If you want to load data to view, you should use new Subject in your service. For example:
export class PostService {
subject = new Subject();
constructor(private httpClient: HttpClient) {}
const httpRequest = new HttpRequest(
'GET',
'/your-url',
body,
{
headers: new HttpHeaders().set('Content-Type', 'body'),
}
);
this.httpClient.request(httpRequest).subscribe((res) => {
if (res.type) {
this.subject.next(res.body);
}
});
return this.subject;
}
In component:
export class PostsComponent implements OnInit {
posts: any;
constructor(private postService: PostService) { }
ngOnInit() {
this.getPosts();
}
private getPosts() {
this.posts = this.postService.getPosts();
}
}
In view:
<app-post-item
class="col-md-4"
*ngFor="let post of posts | async"
[post]="post">
</app-post-item>
Upvotes: 2
Reputation: 1984
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;
})
};
Upvotes: 7
Reputation: 73384
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.
Upvotes: 2