Home > Software engineering >  Fetched data not rendering in Angular
Fetched data not rendering in Angular

Time:02-03

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

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');
   }
}

CodePudding user response:

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>
  • Related