Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fetched data not rendering in Angular

I’m trying to fetch data From an API using Angular. I can see in the console log that the data is fetched, however the data doesn’t render on the page. Help appreciated.
Here is my code:

app.component.html

<p>{{data.Name}}</p>
<p>{{data.Habitat}}</p>
<p>{{data.Status}}</p>

app.component.ts

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import { ApiserviceService } from './Service';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent {
 title = 'apidata';
 data:any;
 constructor(private _apiservie:ApiserviceService){}

ngOnInit(){
 this._apiservie.getdata().subscribe(res=>{
   this.data=res;
   console.log(res)
 })

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';

@NgModule({
 declarations: [
   AppComponent
 ],
 imports: [
   BrowserModule,
   HttpClientModule,
 ],
 providers: [],
 bootstrap: [AppComponent]
})
export class AppModule { }

service.ts

import { Injectable } from '@angular/core';

@Injectable({
   providedIn: 'root'
})
export class ApiserviceService {
constructor(private _http:HttpClient){}
   getdata(){
return this._http.get('https://mocki.io/v1/8f823c35-8ae8-4fb5-a84b-cf7dce59c7a7');
   }
}

>Solution :

app.component.ts

import { ApiserviceService } from './Service';

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent {
 title = 'apidata';
 data:any;
 constructor(private _apiservie:ApiserviceService){}

ngOnInit(){
  this.getinfo()
 
}
getinfo(){
this._apiservie.getdata().subscribe(res=>{
  this.data=res;
  console.log(res)
})
}
}

app.component.html

<div *ngFor="let item of data">
    <p>{{item.Name}}</p>
     <p>{{item.Habitat}}</p> 
     <p>{{item.Status}}</p>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading