Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return HttpClient subscribe data to a component

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, …}

like image 750
Rahul Dagli Avatar asked Sep 01 '25 16:09

Rahul Dagli


2 Answers

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;
   })
};
like image 150
Preethi Avatar answered Sep 04 '25 07:09

Preethi


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.

like image 32
gsamaras Avatar answered Sep 04 '25 05:09

gsamaras