调用json数据时出错。

27 浏览
0 Comments

调用json数据时出错。

我正在尝试调用(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;
   constructor(private http:Http){
         this.http.get('./data.json')
        .map(response => response.json().screenshots)
        .subscribe(res => this.spaceScreens = res);
      }
 }

我得到了以下错误

error TS2339: 类型'Observable'上不存在属性'map'

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

 import 'rxjs/add/operator/map'

import 'rxjs/Rx';

这些解决方案在这个帖子中被标记为正确(Property 'map' does not exist on type 'Observable'

仍然没有结果。

这是(customer.component.html)文件

         
          
            
                    
              {{ spaceScreen.description }}
            
          

这是在名为data的文件夹中的(app.json)文件

{

"screenshots":[

{

"img":"assets/img/json_1.jpg",

"description":"美国"

},

{

"img":"assets/img/json_2.jpg",

"description":"英国"

},

{

"img":"assets/img/json_3.jpg",

"description":"印度"

}

]

}

现在出现了以下错误

    ERROR TypeError: 无法读取未定义的属性'description'  

0
0 Comments

在调用json数据时出现问题。问题的原因是从RxJS 5.5开始,需要使用pipeable operators,并将map操作符传入pipe函数中。解决方法是从rxjs/operators中导入map操作符,并像下面的示例代码一样使用:

import { map } from 'rxjs/operators';
this.http.get('./data.json').pipe(
    map(response => response.json().screenshots)
).subscribe(res => this.spaceScreens = res);

如果这个回答或任何其他回答解决了你的问题,请考虑点击勾选标记以接受它。这将向更广泛的社区表明你已经找到了解决方案,并给予回答者和你自己一些声望。这并不是义务性的。

也许你在其他地方也使用了.description,除了视图之外?我没有在任何地方使用.description,但没有文本,只有图片。

0
0 Comments

(Error in calling JSON data) 这个问题出现的原因是Observable类型上不存在属性'map'。解决方法是需要在所有操作符周围添加.pipe()方法。具体操作如下:

将代码:

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

修改为:

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

同时,还需要按照以下方式导入map操作符:

import { map } from 'rxjs/operators';

这样就能解决问题了。

另外,如果在模板中使用了安全导航操作符(?.),例如:

{{ spaceScreen?.description }}

,以及使用了图片的,同样需要进行相同的修改。

此外,还可能出现了以下错误信息:Response {_body: "...", status: 404, ok: false, statusText: "Not Found", headers: Headers, ...}。这表示无法找到指定的JSON文件。解决方法是将JSON文件放在assets文件夹中。

希望以上内容能够解决你的问题。如果还需要继续讨论,请点击此处进入聊天室。另外,如果在模板中文本无法加载,或者

{{ spaceScreen?.description }}

和图片重叠等问题,请检查相应的代码。

0