0

I'm trying to pass a JSON from my api service to any component without subscribing in the component it self. What happens it that I get the data inner the .subscribe without any problem in the api.service.ts function But when I'm trying to get that data outside of it returns something else

Here is the code:

api.service.ts


import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class ApiService {

constructor(private http: HttpClient) {}

public getInfo(URL: string): Observable<any> {
  return this.http.get( URL )
    .pipe(
      tap( (fetchJSON) => JSON.stringify(fetchJSON) )
    )
}

// I'm planning to create more functions like this one to get particular data:

public getParticularData(){
  let infoJSON;
  let URL = "https://jsonplaceholder.typicode.com/posts";
  infoJSON = this.getInfo(URL)
  .subscribe(data =>{ console.log(data) });
  // the console.log(data) inside the .subscribe returns my Json data perfectly

  return infoJSON;
  //this returns: Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null, …}

}

}

home.component.ts

*the rest of the imports are here don't worry*
import { ApiService } from '@api/api.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class homeComponent implements OnInit {

constructor( private ApiService: ApiService){

 JSON = this.ApiService.getParticularData();
 console.log(JSON) // returns undefined

}



}
Carlos Cavero
  • 3,011
  • 5
  • 21
  • 41
mentamarindo
  • 539
  • 9
  • 16

1 Answers1

1

You are making two mistakes:

  1. You are returning subsciption.

  2. You are trying to access data synchronously but ajax is async.

As a simple solution, dont subscribe inside the service but in the component

public getParticularData(){
  let infoJSON;
  let URL = "https://jsonplaceholder.typicode.com/posts";
  infoJSON = this.getInfo(URL)
  .map(data =>{ console.log(data) });
  // the console.log(data) inside the .subscribe returns my Json data perfectly

  return new Promise((resolve)=>{
      infoJSON.subscribe((data)=>resolve(data))
  })

}

component:

   async myMethod(){
    let data = await this.ApiService.getParticularData();
    console.log(data);
   }
dasfdsa
  • 7,102
  • 8
  • 51
  • 93
  • Well, I already did that. But I'm trying to avoind subscribing in the component(s). Because I will have to subscribe in ALL the other components in which I will need the same data. Got it? – mentamarindo Apr 02 '19 at 16:24
  • you can use async await...i edited my answer – dasfdsa Apr 02 '19 at 16:35