【发布时间】:2017-03-10 10:03:21
【问题描述】:
如何映射和使用作为单个对象而不是数组的 JSON 响应?
最近,我开始向我正在处理的项目中添加一个新功能,该功能应该从 API 获取 JSON 响应,并使用其中的数据填写一个简单的模板。应该不难吧?嗯,不……但是,是的……
JSON 响应的模拟版本:
{
"id": 1,
"name": "Acaeris",
}
profile.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Profile } from './profile';
/**
* This class provides the Profile service with methods to read profile data
*/
@Injectable()
export class ProfileService {
/**
* Creates a new ProfileService with the injected Http.
* @param {Http} http - The injected Http.
* @constructor
*/
constructor(private http: Http) {}
/**
* Returns an Observable for the HTTP GET request for the JSON resource.
* @return {Profile} The Observable for the HTTP request.
*/
get(): Observable<Profile> {
return this.http.get('assets/profile.json')
.map(res => <Profile>res.json())
.catch(this.handleError);
}
/**
* Handle HTTP error
*/
private handleError (error: any) {
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Observable.throw(errMsg);
}
}
profile.component.ts
import { Component, OnInit } from '@angular/core';
import { ProfileService } from '../services/profile/profile.service';
import { Profile } from '../services/profile/profile';
/**
* This class represents the lazy loaded ProfileComponent
*/
@Component({
moduleId: module.id,
selector: 'sd-profile',
templateUrl: 'profile.component.html',
styleUrls: ['profile.component.css'],
})
export class ProfileComponent implements OnInit {
errorMessage: string;
profile: Profile;
/**
* Creates an instance of the ProfileComponent with the injected
* ProfileService
*
* @param {ProfileService} profileService - The injected ProfileService
*/
constructor(public profileService: ProfileService) {}
/**
* Get the profile data
*/
ngOnInit() {
this.getProfile();
}
/**
* Handles the profileService observable
*/
getProfile() {
this.profileService.get()
.subscribe(
data => this.profile = data,
error => this.errorMessage = <any>error
);
}
}
profile.ts
export interface Profile {
id: number;
name: string;
}
我只是尝试使用{{profile.name}} 输出它,但这最终导致控制台显示大量错误消息并且没有输出。如果我在加载后尝试检查profile 的内容,它会告诉我它是undefined。
但是,这是令人困惑的部分。如果我将所有Profile 引用替换为Profile[],将JSON 包装在一个数组中,添加*ngFor="let p of profile" abd 使用{{p.name}} 一切正常。不幸的是,在实际完成的应用程序中,我无法控制 JSON 格式。那么,与作为对象数组处理相比,尝试将其作为单个对象处理时,我做错了什么?
【问题讨论】:
标签: javascript json angular typescript