使用map()将json数据转换为对象

时间:2017-11-28 19:41:21

标签: javascript angular

我有数据服务,它将伪数据作为json(私有mockData函数)返回。 由于json数据结构与MyPerson对象匹配,因此尝试使用.map(res => res as MyPerson));将json数据强制转换为MyPerson对象 这不起作用,因为我收到数据无法转换为MyPerson对象的错误。

  

我的问题是:我如何使用这个json数据映射到MyPerson对象   地图功能?

@Injectable()
export class DataService {
    person: MyPerson;

    constructor(private http: Http) {
        this.person = new MyPerson();
    }

    getData(): Observable<MyPerson> {
        return Observable.from([this.mockData()]
            .map(res => res as MyPerson)); /// ERROR?
    }

    private mockData() {
        return {
            "Id": 100,
            "firstName": "John",
            "lastName": "Conor",         
            "address": {
                "postalAddress": {
                    "Streetline": "Long street",
                    "Suburb": "some suburb",
                    "City": "Boston",
                    "Province": "MA"
                },
                "residentialAddress": {
                    "Streetline": "Short street",
                    "Suburb": "my suburb",
                    "City": "New Jersey",
                    "Province": "N/A"
                }
            },
            "Status": OK            
        }
    };
}

 export class MyPerson {
        Id: number;    
        firstName: string;
        lastName: string;    
        address: {
            residentalAddress: Address;
            postalAddress: Address;
        }    
    }

export class Address {    
    public StreetAddress: string;
    public Suburb: string;
    public City: string;
    public Province: string;

    constructor(street: string, suburb: string, city: string, province: string){
        this.StreetAddress = street;
        this.Suburb = suburb;
        this.City = city;
        this.Province = province;
    }
}

2 个答案:

答案 0 :(得分:1)

您错过了i课程residentialAddress中的MyPerson,而您在模拟数据中使用的是StreetLine而不是StreetAddress。已修复stackblitz

答案 1 :(得分:0)

如果你定义了私有的mockData():MyPerson的返回类型,它会告诉你知道的Typescript,并且可以控制返回什么数据,并且不需要通过尝试推断出类型来弄清楚它。