Search code examples
angularangular-materialangular6angular-pipe

Error in calling json data


I am trying to call the data present in (data/app.json) file.

Below is component(customer.component.ts)file

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http'; 


@Component({
   selector: 'ylb-customer',
   templateUrl: './customer.component.html',
   styleUrls: ['./customer.component.css']
})
export class CustomerComponent  {

   spaceScreens: Array<any>;

   constructor(private http:Http){
         this.http.get('./data.json')
        .map(response => response.json().screenshots)
        .subscribe(res => this.spaceScreens = res);
      }


 }

This error I got

error TS2339: Property 'map' does not exist on type 'Observable'.

For the error i tried this solution too

 import 'rxjs/add/operator/map'

and

import 'rxjs/Rx';

Which were marked as correct in this post(Property 'map' does not exist on type 'Observable<Response>')

Still no result.

this is (customer.component.html)file

         <div>
          <mat-card class="example-card">
            <mat-card-header>
              <div mat-card-avatar class="example-header-image" *ngFor="let spaceScreen of spaceScreens; let i = index">
                    <img src="{{ spaceScreen.img }}">
              </div>
              <mat-card-title><p>{{ spaceScreen.description }}</p></mat-card-title>
            </mat-card-header>
          </mat-card>
          </div>

This is (app.json) present in inside folder called data

     {   
       "screenshots":[ 
         {
            "img":"assets/img/json_1.jpg",
            "description":"USA"
        },

        {
            "img":"assets/img/json_2.jpg",
            "description":"UK"
        },

        {
            "img":"assets/img/json_3.jpg",
            "description":"INDIA"
        }

    ]        
  }

Now getting this error

    ERROR TypeError: Cannot read property 'description' of undefined  

Solution

  • Property ‘map’ does not exist on type Observable. The problem was related to the fact that you need to add pipe around all operators.

    Change this,

    this.http.get('./data.json').map(data => {})
    

    to this

    this.http.get('./data.json').pipe(map(data => {}))
    

    And

    Import map like this,

    import { map } from 'rxjs/operators';
    

    It will solve your issues.