Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
153
rated 0 times [  155] [ 2]  / answers: 1 / hits: 18405  / 6 Years ago, mon, march 26, 2018, 12:00:00

I have an AFS observable which I can show in my frontend like this:



constructor(
public fb: FirebaseProvider,
) {
this.group = this.navParams.get('group');
this.contactsList = this.fb.getContactsByGroup(this.group.id);
}


My fb service:



getContactsByGroup(groupId: string):Observable<Contact[]> {
return this.afs.collection<Contact>(`groups/${groupId}/contacts`).valueChanges();
}


Then my template:



<single-contact-list-item 
[contactId]=contact.id
(goToModalEvent)=onGoToModal($event)
*ngFor=let contact of contactsList | async>
</single-contact-list-item>


Now I have a textarea which when submitted triggers an event. What I want to do is loop through each item in the Observable (contactsList) and get a property, for example:



public sendSMS(): void {
this.contactsList.forEach(contact => {
console.log(contact.number); // nothing!
})
//this.deviceProvider.sendSMS(this.contactsList, this.message);
}


I feel like the issue is that by using the async pipe in the template the Observable is already subscribed. Any help appreciated.


More From » angular

 Answers
7

You will need to manually get the result of Observable in a variable in you component.



constructor(
public fb: FirebaseProvider,
) {
this.group = this.navParams.get('group');
this.fb.getContactsByGroup(this.group.id).subscribe(list =>
this.contactsList = list);
}


and change your template to render only when the contactList is available. And iterate over the the list.



<ng-container *ngIf=contactsList>
<single-contact-list-item
[contactId]=contact.id
(goToModalEvent)=onGoToModal($event)
*ngFor=let contact of contactsList>
</single-contact-list-item>
<ng-container>


By doing this your function sendSms will work as it is and will get the list of conatcts.



public sendSMS(): void {
this.contactsList.forEach(contact => {
console.log(contact.number); // WORKING!!!!
})
//this.deviceProvider.sendSMS(this.contactsList, this.message);
}

[#54856] Wednesday, March 21, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
anders

Total Points: 295
Total Questions: 106
Total Answers: 104

Location: Angola
Member since Wed, Apr 13, 2022
2 Years ago
;