Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 Trying to iterate over array of objects

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);
          }
        )
      );
  }
}
like image 720
rossarian Avatar asked May 12 '18 13:05

rossarian


1 Answers

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.

like image 78
s.alem Avatar answered Oct 20 '22 11:10

s.alem