0
I’m trying to get some database information through the function get(), but when I try to run it, gets the error:
ERROR TypeError: Cannot read property 'get' of undefined
at HomeTabPage.push../src/app/home-tab/home-tab.page.ts.HomeTabPage.ngOnInit (home-tab.page.ts:18)
In the * ngFor I tried using the Elvis parameter, but it didn’t work. I already passed my main function of ngOnInit and declared another function to reference, but it did not work.
Typescript/HTML
export class HomeTabPage implements OnInit {
public advertList: Array<any>;
constructor(private navCtrl: NavController, public adService: AdvertisingService) {
}
ngOnInit(){
this.adService.getAdAllList().get().then(advertListSnapshot => {
this.advertList = [];
advertListSnapshot.forEach(snap =>{
this.advertList.push({
id: snap.id,
name: snap.data().name,
price: snap.data().price,
description: snap.data().description,
image: snap.data().picture
});
});
});
}
}
<ion-list>
<ion-item *ngFor="let advert of advertList">
<ion-thumbnail slot="start">
<ion-img src="{{advert?.image}}"></ion-img>
</ion-thumbnail>
<ion-label>
<h2 >{{advert?.name}}</h2>
<h3 >{{advert?.price}}</h3>
<p >{{advert?.description}}</p>
</ion-label>
</ion-item>
</ion-list>
service ts.
export class AdvertisingService {
public adAllListRef: firebase.firestore.CollectionReference;
constructor() {
firebase.auth().onAuthStateChanged(user => {
if (user) {
this.adAllListRef = firebase.firestore().collection(`/adverts/adAll/adList`);
}
});
}
//cRud -> Read
getAdAllList(): firebase.firestore.CollectionReference {
return this.adAllListRef;
}
}
And what the method
getAdAllListreturns? Because by the error we can deduce that this method is not returning anything, and so the error when you invoke thegeton that return.– Andre
makes sense what you said. I put the code service ts. to check. I may be missing something I still can’t see. Should I pass some parameter?
– Caio Costa
That function
onAuthStateChangedIt’s asynchronous, isn’t it? The propertyadAllListRefwill only be started after this function receives the return from Fire Base. Will the problem is not happening because you are invoking the methodgeton the propertyadAllListRefbefore it is even started? Another possibility is that the property has not been started becauseuserisnull.– Andre
After you talked about the
userwasnullI decided to log back into the app and it worked perfectly. Thank you so much for the light! I will fix an error inHMTLthat instead of<ion-img src="advert?.image"></ion-img>the image only appeared with<ion-img src="{{advert?.image}}"></ion-img>– Caio Costa