5

I'm trying to iterate over an array of objects in one of my components in 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;
  }

}

Eventually I want to add a property to every object in this array, but I'm stuck at just trying to do anything to get to work with it.

I don't think getContacts() is an observable since I've already subscribed to the http request and created my array of contacts objects from the data.

Here's what's in 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);
          }
        )
      );
  }
}
3
  • Is getContacts() returning an Observable? Commented May 12, 2018 at 13:12
  • Assuming getContacts() is an observable, you will need to subscribe to it and then you will be able to perform the iteration... post getContacts() Commented May 12, 2018 at 13:22
  • @s.alem yes it is. Commented May 12, 2018 at 13:22

1 Answer 1

15

You need to subscribe to the observable in order to iterate.

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

BUT it looks like you are just learning your way in Angular, I suggest to subscribe as little as possible and try to use async pipe instead. There are a lot of material about it on the net.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the help @s.alem. I've updated my question with the contents of my contact.service.ts file. As opposed to my earlier reply to your first comment, I don't think getContacts() is an observable, it just returns the array of Contact objects that are stored in the service (see contact.service.ts file above for what I'm talking about). Again, thanks a lot for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.