【问题标题】:Angular 2 - Json parse to TypeScript ObjectAngular 2 - Json 解析为 TypeScript 对象
【发布时间】:2017-01-02 21:21:02
【问题描述】:

我是 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>

【问题讨论】:

  • 错误是什么?
  • 没有错误,只是在我尝试访问时没有出现在屏幕上。调试代码的时候可以看到信息是json格式的,但是做psrse的时候却无法访问。

标签: angularjs json http parsing angular


【解决方案1】:
<h1 class="name">{{mainInformation?.id?.user?.name}}</h1>

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

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

【讨论】:

  • class User doesn't have a name property - 这是一个错误
  • 谢谢,我只是没有意识到这个错误。现在工作了:)
【解决方案2】:

我认为你的意思是 你检查他是否是instanceof,然后投他

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

【讨论】:

    猜你喜欢
    • 2017-10-15
    • 1970-01-01
    • 2017-03-18
    • 2021-05-15
    • 2016-07-27
    • 2019-06-27
    • 2020-05-02
    • 2015-09-27
    • 2021-02-06
    相关资源
    最近更新 更多