【问题标题】:Angular 5 cannot display interface object to htmlAngular 5 无法将界面对象显示为 html
【发布时间】:2018-07-02 14:30:01
【问题描述】:

我的服务器给了我这样的 json。

[
{
    "userId": 11,
    "positionId": 2,
    "emailAddress": "ada.lovelace@gmail.com",
    "username": "adalovelace",
    "createdBy": 1,
    "createdAt": "2018-01-06 13:43:18",
    "updatedBy": null,
    "updatedAt": "2018-01-06 13:43:18",
    "profile": {
        "userProfileId": 1,
        "userId": 11,
        "displayName": "adalovelace",
        "location": null,
        "title": null,
        "imageUrl": null,
        "about": null,
        "threadCount": 0,
        "threadPostCount": 1,
        "threadKarma": 0,
        "threadPostKarma": 2
    }
}
]

我的.ts文件是这样的,我去掉了很多不相关的代码。

import { UserService } from '../_shared/services/user.service';
import { UserInterface } from '../_shared/interfaces/user.interface';

export class ProfileComponent implements OnInit, OnDestroy {

private currentUser = <UserInterface>{};

public username: string;

public userProfile = <UserInterface>{};

ngOnInit() {
    this.userSubcription = this.userService.showProfile(this.username)
        .subscribe((userProfile: UserInterface) => {
            this.userProfile = userProfile;
            console.log(this.userProfile); // has value!
        }, error => {
            console.log(error);
        });
}

}

.html 文件

<section id="profile">
<div class="container">
    <div class="row">
        <div class="col">
            <h2>{{userProfile.userId}}</h2>
            <h2>{{userProfile.profile.dsplayName}}</h2>
        </div>
    </div>
</div>

它没有显示任何东西。 userProfile.profile.dsplayName 甚至给了我错误。它说未定义。

用户界面如下所示。

import { UserProfileInterface } from './user-profile.interface';

export interface UserInterface {
userId: number;
token: string;
username: string;
emailAddress: string;
createdBy: string;
createdAt: string;
updatedBy: string;
updatedAt: string;

positionId: number;
password: string;
confirmPassword: string;

profile: UserProfileInterface;
}

是不是因为我用的是界面?我有另一个类似的页面,它使用内部接口数组的接口,但它可以工作。

【问题讨论】:

    标签: json angular typescript angular5


    【解决方案1】:

    您的服务器返回 json 数组。试试下面的代码 sn-p

    <section id="profile">
    <div class="container">
        <div class="row">
            <div class="col">
                <h2>{{userProfile[0].userId}}</h2>
                <h2>{{userProfile[0].profile.dsplayName}}</h2>
            </div>
        </div>
    </div>
    

    【讨论】:

      猜你喜欢
      • 2018-12-05
      • 1970-01-01
      • 2011-12-21
      • 1970-01-01
      • 2018-11-23
      • 2020-07-10
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多