I'm currently utilizing Angular 5 to fetch data from JsonPlaceholder API.
Initially, I set up the service and included:
import { HttpClientModule } from '@angular/common/http';
This is the service implementation:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class DataService {
private ROOT_URL = 'http://jsonplaceholder.typicode.com';
constructor(private http: HttpClient) {}
getPosts() {
this.http.get(`${this.ROOT_URL}/posts`).subscribe(data => {
return data;
});
}
}
Then, in my app.component.ts file:
import { Component, OnInit } from '@angular/core';
import { DataService } from '../../services/data.service';
@Component({
selector: 'app-root',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class AppComponent implements OnInit {
data;
constructor(private dataService: DataService) {
this.data = dataService.getPosts();
console.log(this.data);
}
ngOnInit() {
}
}
However, when checking the console, it keeps displaying 'Undefined'.
Can someone please help me figure out what's wrong?