Angular 6尝试迭代对象数组

时间:2018-05-12 13:09:05

标签: angular typescript

我试图在ngOnInit中的一个组件中迭代一组对象:

@Component({
  selector: 'app-contact-list',
  templateUrl: './contact-list.component.html',
  styleUrls: ['./contact-list.component.css']
})
export class ContactListComponent implements OnInit {
  contacts: Contact[] = [];
  filteredContacts = this.contacts.slice(); // Copy of Contacts

  constructor(private contactService: ContactService) {}

  ngOnInit() {
    this.contacts = this.contactService.getContacts();
    console.log(this.contacts); 
    console.log(typeof(this.contacts)); // object
    for(let contact of this.contacts) {
      console.log(contact); // Does not return anything
    }
  }

  filterContacts = (contacts) => {
    this.filteredContacts = contacts;
  }

}

最终我想为这个数组中的每个对象添加一个属性,但是我只是想尝试做任何事情来使用它。

我不认为getContacts()是一个可观察的,因为我已经订阅了http请求并从数据中创建了我的联系人对象数组。

以下是contact.service.ts:

中的内容
@Injectable()
export class ContactService {
  private contact: Contact;
  private contacts: Contact[] = [];

  activeContact = new EventEmitter<Contact>();

  constructor(private http: Http) {
    this.onGetContactsFromServer() // Subscribe to the getContacts operator
      .subscribe(
        (response) => this.mapContacts(response),
        (error) => console.log(error)
      );
  }

  getContacts() {
    return this.contacts;
  }

  mapContacts(response) {
    // Map the getContacts response to a Contact[]
    for ( let c of response ) {
      this.contact = new Contact(
        +c.id, +c.account_id, c.title, c.first_name, c.last_name,
        c.email, c.phone_number, c.address, c.city, c.country,
        c.postal_code, c.created, c.modified
      );
      this.contacts.push(this.contact);
    }
  }

  onGetContactsFromServer() {
    return this.http.get('http://127.0.0.1:8000/app-contacts.json')
      .pipe(
        map(
          (response: Response) => {
            const data = response.json();
            return data;
          }
        )
      )
      .pipe(
        catchError(
          (error: Response) => {
            return throwError(error);
          }
        )
      );
  }
}

1 个答案:

答案 0 :(得分:9)

您需要订阅observable才能进行迭代。

ngOnInit() {
  this.contactService.getContacts().subscribe(contacts => {
    this.contacts = contacts;
    this.contacts.forEach(contact => {
      console.log(contact);
    });
  });
}

但是看起来你只是在Angular中学习你的方式,我建议尽可能少地订阅并尝试使用async管道。网上有很多关于它的资料。