【发布时间】:2018-06-10 18:56:03
【问题描述】:
我目前遇到的问题是来自我的 Web 服务调用的数据未正确绑定到我的角度模型(或者至少这是我目前认为的问题)。这个简单的示例说明了我的问题,导致页面上呈现了 <li></li> 元素,但是它们都是空白的,并且其中包含空的 span。有 3 个元素,因为我的数据库中有 3 个条目。我已经以我能想到的各种方式调试了这个问题,但一直无法找到导致此问题的原因。下面,您可以找到我的简单 Angular 组件、它的 html 模板、我的打字稿模型,以及从我的 Web 服务返回的 3 个 json 对象中的一个示例:
角度组件:
import { Component, OnInit } from "@angular/core";
import { Router } from "@angular/router";
import { BabyProfile } from "./baby-profile";
import { BabyProfileService } from "./baby-profile.service";
@Component({
selector: "baby-profile-list",
templateUrl: './app/baby-profile/baby-profile-list.component.html'
})
export class BabyProfileListComponent implements OnInit{
title: string;
selectedProfile: BabyProfile;
babyProfiles: BabyProfile[];
debug: string;
constructor(private babyProfileService: BabyProfileService,
private router: Router) { }
ngOnInit() {
this.babyProfileService.getAll().subscribe(
babyProfiles => this.babyProfiles = babyProfiles);
}
edit(babyProfile: BabyProfile) {
this.router.navigate(['babyprofile/', babyProfile.Id]);
}
}
组件的html模板:
<h2>{{title}}</h2>
<div>
<ul class="list-group">
<li class="list-group-item" *ngFor="let babyProfile of babyProfiles"
(click)="edit(babyProfile)">
<span>{{babyProfile.FirstName}} {{babyProfile.LastName}}</span>
<span>{{babyProfile.BirthDate}}</span>
</li>
</ul>
</div>
打字稿模型:
export class BabyProfile {
constructor(
public Id: number = 0,
public FirstName: string,
public LastName: string,
public MiddleName: string,
public BirthDate: Date,
public DateCreated: Date,
public InactiveDate: Date
) { }
}
以及我的 Web 服务返回的 3 个对象中的 1 个的属性示例(注意:此屏幕截图是将 babyProfiles => this.babyProfiles = babyProfiles 替换为 babyProfiles => console.log(babyProfiles) 然后在控制台中检查结果):
还有一个空的<li><span> </span><span></span></li> 输出示例:
我注意到我的 typescript 模型和 web 服务响应之间的大小写不同,并更改了 typescript 模型和 html 模板以使用小写的驼峰属性名称,但这并没有解决问题。我在这里错过了什么?
感谢所有帮助。
【问题讨论】:
-
您可以尝试通过将绑定更改为
{{babyProfile | json}}来进行调试,这将输出babyProfile 的JSON。然后,您可以确保它符合您的期望。要检查的另一件事是您的服务正在返回一个对象,而不仅仅是一个字符串 -
只需将模板中的
FirstName和BirthDate替换为firstName和birthDate -
user184994 是对的。从 ngFor 创建的结构看来,您只是对数据结构有一些问题。像user184994所说的那样显示它,你会看到问题出在哪里。
-
@user184994 我对 angular 还很陌生——你能详细说明一下
{{babyProfile | json}}会去哪里吗?我已经找到了我的问题的答案,但我想知道,这样我就可以更好地调试任何未来的问题。我发现在这种环境中调试客户端问题比在 asp.net mvc/razor 中要困难得多 -
它会在你的范围内
标签: json angular typescript angular-components