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