Search code examples
angulartypescripthttpmodule

Angular : can't get data from url using HttpClientModule


In my app, my objective is to fetch data from this URL below and display it in my app. https://jsonplaceholder.typicode.com/posts/1

My problem is data is not showing in my app, Console says something that i don't understand where to correct.

firefox console (ctrl+shift+k)

Angular is running in the development mode. Call enableProdMode() to enable the production mode. core.js:40471

[WDS] Live Reloading enabled. client:52

ERROR Error: "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."
    Angular 21
    RxJS 5
    Angular 9
core.js:5882:19

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { HttpClientModule } from '@angular/common/http';

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

app.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  readonly ROOT_URL = 'https://jsonplaceholder.typicode.com';
  posts: any;
  constructor(private http: HttpClient) {

  }
  getPosts() {

     this.posts = this.http.get(this.ROOT_URL + '/posts/1');
  }
}

**app.component.html**

<h1>Angular HTTP Basic</h1>

<button (click)="getPosts()"> get</button>

<div *ngFor = "let post of posts">
  {{ post | json }}
</div>

This should be a simple work, but vs code didn't give me any error and i don't get it what my browser console means. Please point out what went wrong.


Solution

  • You need to subscribe to your observable:

      posts: any[] = [];
    
      getPosts() {
         this.http.get(this.ROOT_URL + '/posts/1').subscribe((post) => {
           this.posts = [post];
         });
      }
    
    

    Or you can use the power of observables and angular together:

      import { map } from 'rxjs/operators';
      import { Observable } from 'rxjs';
    
      posts: Observable<any[]>;
    
      getPosts() {
         this.posts = this.http.get(this.ROOT_URL + '/posts/1').pipe(
           map((post) => [post])
         );
      }
    
    <div *ngFor = "let post of posts | async">
      {{ post | json }}
    </div>