Angular中Http Get请求后无法使用接口数组属性的问题
我来帮你梳理下你遇到的几个关键问题,一步步解决就能正常渲染Widget数组了:
1. 修复JSON文件格式错误
你的JSON文件现在用大括号包裹多个对象,不符合数组格式规范,应该改成方括号包裹的数组结构:
[ { "id": 1, "layout": 1, "col": 1, "row": 1 }, { "id": 2, "layout": 1, "col": 1, "row": 2 } ]
2. 修正Service中的类型转换错误
你的loadDashboard方法声明返回Observable<Interface[]>,但map回调里却把响应转换成了单个Interface对象,这会导致类型不匹配。要改成数组类型的断言:
import { Http, Response, Headers } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import "rxjs/Rx"; import { Interface } from './interface'; @Injectable() export class Service { private url = "path/to/your/JSON.json"; // 记得替换成实际的JSON文件路径 loadDashboard(): Observable<Interface[]> { return this.http.get(this.url) .map((response: Response) => { return <Interface[]>response.json(); // 改为数组类型断言 }) .catch(this.handleError); } private handleError(error: Response){ return Observable.throw(error.statusText); } }
3. 统一Interface的属性名
你的Interface里用的是column,但JSON字段是col,这会导致数据无法正确映射,把Interface改成和JSON一致的属性名:
export interface Interface { layout: number; id: number; col: number; // 改为col,和JSON字段对应 row: number; }
4. 处理异步操作时机 & 正确遍历数组
Angular的Http请求是异步执行的,你现在把push和外部的console.log放在subscribe回调外面,这时候_array还没被赋值,自然会返回undefined。另外_array是数组,不能直接取this._array.id,需要遍历每个元素:
import { Component, OnInit } from '@angular/core'; import { Service } from './service'; import { Interface } from './interface'; export class YourComponent implements OnInit { // 给组件起一个具体的名称 _array: Interface[] = []; // 初始化空数组,避免undefined Widget: Array<{id: number, col: number, row: number, layout: number}> = []; // 补充layout属性 constructor (private service: Service) { } getDashboard(){ this.service.loadDashboard() .subscribe(loadArray => { this._array = loadArray; console.log(this._array); // 这里能拿到正确的返回数据 // 遍历数组,将每个元素添加到Widget中 this._array.forEach(item => { this.Widget.push({ id: item.id, layout: item.layout, col: item.col, row: item.row }); }); console.log(this.Widget); // 此时Widget已填充数据 }); // 这里的console.log会先执行(因为subscribe是异步),所以会打印undefined,属于正常现象 console.log(this._array); } ngOnInit(){ this.getDashboard(); // 调用组件方法要加this } }
关键总结
- 确保JSON是合法的数组格式
- 异步操作的业务逻辑必须放在
subscribe回调内部 - 类型断言要和方法声明的返回值类型匹配
- Interface的属性名要和JSON字段完全一致
内容的提问来源于stack exchange,提问作者Dung Ngo
相关产品推荐
相关产品推荐

