角度数据未正确绑定到模型

时间:2017-12-30 20:49:35

标签: json angular typescript angular-components

我目前遇到的问题是来自我的网络服务电话的数据没有正确绑定到我的角度模型(或者至少是我目前认为的问题)。这个简单的例子说明了我的问题导致<li></li>元素在页面上呈现,但它们都是空白的,并且在它们内部包含空的跨度。有3个元素,因为我的数据库中有3个条目。我已经按照我能想到的每一种方式调试了这个问题,并且无法找到原因。下面,您可以找到我的简单角度组件,它的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)然后在控制台中检查结果来获取的: enter image description here

以及空<li><span> </span><span></span></li>输出的示例: enter image description here

我注意到我的打字稿模型和Web服务响应之间的大小写不同,并且改变了打字稿模型和html模板以使用较低的驼峰案例属性名称,但这并没有解决问题。我在这里缺少什么?

感谢所有帮助。

2 个答案:

答案 0 :(得分:1)

我猜问题在于订阅内部,将其更改如下

 ngOnInit() {
   this.babyProfileService.getAll().subscribe((babyProfilesResult) => {
        this.babyProfiles = babyProfilesResult;
    });
}

答案 1 :(得分:-1)

我认为你还没有在templateUrl下面的@Component装饰器中添加提供程序。要调用和使用组件中的任何服务,我们需要添加提供程序。所以,尝试添加相同的内容。

相关问题