簡體   English   中英

Angular 2-Json解析為TypeScript對象

[英]Angular 2 - Json parse to TypeScript Object

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

似乎您正在嘗試訪問user.name但是User類沒有name屬性:

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

我認為您的意思是,您檢查他是否為instanceof,然后將其拋棄

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM