简体   繁体   中英

Angular 2 - Json parse to TypeScript Object

I'm new in Angular 2 and also in TypeScript, I've been going through many articles and tutorials, but I have not found a solution for my problem yet.

I'm making an HTTP call using Angular 2 libraries and it works fine, so I receive a JSON in response, when I make the parse from JSON to TypeScript it does not work for inner objects in classes, like the following exemple:

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

class Class2 {
   name: String;
}

When I try to access the "id" attribute from Class1 it works fine, but when I try to access the "object.name" it doesn't work.

My code:

@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>
<h1 class="name">{{mainInformation?.id?.user?.name}}</h1>

Seems like you're trying to access user.name but the class User doesn't have a name property:

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

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

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

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