有人可以告诉我代码有什么问题吗?角度6

时间:2018-10-14 12:56:33

标签: angular typescript angular6

import { Component, OnInit } from '@angular/core';
import { ContactService } from '../contact.service';
import { Contact } from '../contact';

@Component({
  selector: 'app-contacts',
  templateUrl: './contacts.component.html',
  styleUrls: ['./contacts.component.css'],
  providers: [ContactService]
})
export class ContactsComponent implements OnInit {
  contacts: Contact[];
  contact: Contact;
  first_name: string;
  last_name: string;
  phone: string;

  constructor(public contactService: ContactService) { }

  ngOnInit() {
    this.contactService.getContacts()
      .subscribe(contacts =>
        this.contacts = contacts)
  }

}

我似乎无法理解为什么这行不通。如果我删除构造函数,它将起作用。请帮忙,我正在学习角度知识,所以无法理解我在做什么错。

1 个答案:

答案 0 :(得分:0)

您需要将联系人初始化为空数组,

 contacts: Contact[] = [];

您的模板应如下所示,

<div *ngFor="let contact of contacts">
 <h1>{{contact.first_name}} {{contact.last_name}} {{contact.phone}} </h1>
</div>