Angular 2 - Json解析为TypeScript对象

时间:2017-01-02 21:21:03

标签: angularjs json http parsing angular

我是Angular 2的新手,也是TypeScript的新手,我一直在阅读很多文章和教程,但我还没有找到解决问题的方法。

我正在使用Angular 2库进行HTTP调用并且它工作正常,因此我在响应中收到JSON,当我从JSON到TypeScript进行解析时,它不适用于类中的内部对象,如下例所示:

class Class1 {
   id: number;
   object: Class2;
}

class Class2 {
   name: String;
}

当我尝试从Class1访问“id”属性时,它工作正常,但是当我尝试访问“object.name”时,它不起作用。

我的代码:

@Injectable()
export class ProfileService {

    private mainInformationURL = 'http://localhost:8081/professionalprofile-core/getProfileMainInformation?userId';

    constructor(private http: Http) {}

    getMainInformation(userId: Number) {
        const url = `${this.mainInformationURL}=${userId}`;
        let mainInformation: Profile; 
        let teste: Profile;
        return this.http
                .get(url, { headers: this.getHeaders() })
                .map(response => <Profile>response.json())
                .catch(this.handleError);
    }

    private getHeaders(): Headers {
        let headers = new Headers();
        headers.append('Accept', 'application/json');
        return headers;
    }

    private handleError(error: any): Promise<any> {
        console.log('An error occurred', error); // for demo purposes only
        return Promise.reject(error.message || error);
    }
}



export class ProfileComponent implements OnInit {

    mainInformation: Profile;

    constructor(
        private profileService: ProfileService
    ) {}

    ngOnInit(): void {
        this.getMainInformation();    
    }

    getMainInformation() {
        this.profileService.getMainInformation(1)
            .subscribe(
                data => this.mainInformation = data,
                err => console.log(err),
            );
    }

}

export class Profile {
    id: ProfileId;
    professionalHeadline: String;
    industry: String;
    summary: String;
    mainProfile: Boolean;
    mainContact: Contact;

    constructor(
        id: ProfileId,
        professionalHeadline: String,
        industry: String,
        summary: String,
        mainProfile: Boolean,
        //mainContact: Contact
    ) {
        this.id = id;
        this.professionalHeadline = professionalHeadline;
        this.industry = industry;
        this.summary = summary;
        this.mainProfile = mainProfile;
    }

}

export class ProfileId {
    user: User;
    language: String;

    constructor(
        user: User,
        language: String,
    ) {
        this.user = user;
        this.language = language;
    }
}

export class User {
    id: Number;
    firstName: String;
    surname: String;

    constructor(
        id: Number,
        firstName: String,
        surname: String
    ) {
        this.id = id;
        this.firstName = firstName;
        this.surname = surname;
    }
}



<header class="panel-heading profile_header">
            <img class="img-circle" width="150" height="150">
            <h1 class="name">{{mainInformation?.id?.user?.name}}</h1>
            <div class="main_information">
                <p>{{mainInformation?.professionalHeadline}}, {{mainInformation?.industry}}</p>
                <span class="icon fa-map-marker">Toronto, ON, Canada</span>
                <span class="icon fa-phone icon-margin-left-15px">+11123454577</span>
            </div>
        </header>

2 个答案:

答案 0 :(得分:2)

<h1 class="name">{{mainInformation?.id?.user?.name}}</h1>

您似乎正在尝试访问user.name,但班级User没有name属性:

export class User {
    id: Number;
    firstName: String;
    surname: String;
}

答案 1 :(得分:0)

i think you mean to this you check if he is instanceof and then cast him

if (obj instanceof ObjType) {
            this.obj = <ObjType>obj;
}