How can I get data from an API in ngOnInit. I used *ngIf in html but it doesn't work. I would like to get for now in console the data from an API and now I received undefined. I attached the code. I will appreciate any help. Thanks!
<div>
<app-comp [body]="body" *ngIf="this.body"></app-comp>
</div>
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AgreementsService {
constructor(private http:HttpClient) { }
// Uses http.get() to load data from a single API endpoint
getBodyService(): Observable<any> {
return this.http.get('https://jsonplaceholder.typicode.com/posts');
}
}
import { Component, OnInit, ViewChild } from '@angular/core';
import { AgreementsService } from '../home/agreements/agreements.service';
import { AgreementsComponent } from './agreements/agreements.component';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.sass']
})
export class HomeComponent implements OnInit {
public body;
public bodyData: boolean = false;
constructor(private _agreementsService: AgreementsService) {
}
ngOnInit() {
this.getBody();
console.log(this.body);
}
getBody() {
return this._agreementsService.getBodyService().subscribe(
data => {
this.body = data
},
err => console.error(err),
() => console.log('done loading foods')
)
}
}