调用json数据时出错

问题描述 投票:1回答:3

我试图调用(data / app.json)文件中的数据。

下面是组件(customer.component.ts)文件

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


 }

我得到了这个错误

错误TS2339:类型'Observable'上不存在属性'map'。

对于错误我也尝试了这个解决方案

 import 'rxjs/add/operator/map'

import 'rxjs/Rx';

在这篇文章中被标记为正确(Property 'map' does not exist on type 'Observable<Response>'

仍然没有结果。

这是(customer.component.html)文件

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

这是(app.json)存在于名为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"
        }

    ]        
  }

现在得到这个错误

    ERROR TypeError: Cannot read property 'description' of undefined  
angular angular-material angular6 angular-pipe
3个回答
1
投票

Observable类型中不存在属性“map”。问题与您需要在所有运营商周围添加pipe有关。

改变这个,

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

对此

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

导入这样的地图,

import { map } from 'rxjs/operators';

它将解决您的问题。


1
投票

从RxJS 5.5开始,您需要使用pipeable operators并将map运算符传递到pipe函数。

从中导入map运算符

import { map } from 'rxjs/operators'

并使用像

this.http.get('./data.json').pipe(
        map(response => response.json().screenshots)
    ).subscribe(res => this.spaceScreens = res);

0
投票

这是我应该写的标记

   <mat-card class="example-card" *ngFor="let spaceScreen of spaceScreens; let i = 
             index">
       <mat-card-header>
          <div mat-card-avatar class="example-header-image" >
             <img mat-card-image class="list-img" src="{{spaceScreen?.img}}" >
          </div>
          <mat-card-content class="names">{{ spaceScreen?.name }}</mat-card-content>
       </mat-card-header>
   </mat-card>
© www.soinside.com 2019 - 2024. All rights reserved.