简体   繁体   中英

using map() to convert json data to an object

I have data service which returns fake data as json (private mockData function). Since json data structure matches MyPerson object I'm trying to cast that json data to MyPerson object simple using .map(res => res as MyPerson)); This doesn't work cause I'm getting error that data cannot be converted to MyPerson object.

My question is: how can I map this json data to MyPerson object using map function?

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

You're missing an i in residentialAddress in the MyPerson class, and you're using StreetLine instead of StreetAddress in your mock data. Fixed in stackblitz

如果您定义私有嘲笑数据()的返回类型:MyPerson,它将告诉Typescript您知道并可以控制要返回的数据,而无需通过推断类型来弄清楚。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM