Display data from firebase with ionic - ionic-framework

I have a typescript file with this part of code:
export class HomePage {
createprofile = {} as CreateProfile;
profileData: FirebaseObjectObservable<CreateProfile>;
constructor(private afAuth: AngularFireAuth, private toast: ToastController, private afDatabase: AngularFireDatabase, public navCtrl: NavController) {
}
goToYourItemsListPage(){
this.navCtrl.setRoot("YourItemsListPage");
}
ionViewDidLoad() {
this.afAuth.authState.take(1).subscribe(data => {
if(data && data.email && data.uid){
this.profileData = this.afDatabase.object(`create-profile/${data.uid}`);
//console.log(data);
}else{
this.toast.create({
message: `Could not find authentication details!`,
duration: 3000,
position: "bottom"
}).present();
}
});
}
}
And in home.html I am adding this code:
<h1>Welcome, {{(profileData | async)?.firstName}}!</h1>
But it is not displaying error nor any value it's just: "Welcome !"
What am I missing here?
I'm a newbie to ionic.
Thank you

Related

Cannot use namespace 'NavController'',NgZone',Google,as a type

I am new to ionic app developer, and I am facing this issue: when I open one Component, it is showing error messages, i.e, cannot use namespace as type ionic(NgZone,NavController and googlePlus). Why am I getting this error message?
Here is my code:
export class HomePage {
userProfile: any = null;
zone: NgZone;
constructor(public navCtrl: NavController, private googlePlus: GooglePlus) {
this.zone = new NgZone({});
firebase.auth().onAuthStateChanged( user => {
this.zone.run( () => {
if (user){
this.userProfile = user;
} else {
this.userProfile = null;
}
});
});
}
}
Maybe you forgot to update your project's package. Please try with:
npm install / npm update
Try the Below code : ( The NgZone object can be created as below )
export class HomePage {
userProfile: any = null;
zone: NgZone;
constructor(public navCtrl: NavController, private googlePlus: GooglePlus, private ngZone: NgZone) {
this.zone = ngZone;
firebase.auth().onAuthStateChanged( user => {
this.zone.run( () => {
if (user){
this.userProfile = user;
} else {
this.userProfile = null;
}
});
});
}
}

I have assigned an object during ionViewDidLoad, but the object still empty

I am new to Ionic, I have this problem when trying to pass navParams to other pages. I want to pass the team object from TeamHomePage to TeamDetailPage. but I always got the null. I have check in the ionViewDidLoad, and console it to make sure the team object is assigned, and try to pass a testing object (successfully). Anyone has any idea when is the object of the team went?
<ion-tabs>
<ion-tab tabTitle="Team" [root]='teamDetailTab' [rootParams]='testing' tabIcon="basketball"></ion-tab>
<ion-tab tabTitle="Standings" [root]='standingsTab' [rootParams]='team' tabIcon="podium"></ion-tab>
</ion-tabs>
TeamHomePage.ts
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { TeamDetailPage } from '../team-detail/team-detail';
import { StandingsPage } from '../standings/standings';
#Component({
selector: 'page-team-home',
templateUrl: 'team-home.html',
})
export class TeamHomePage {
public team: any = {}
public teamDetailTab = TeamDetailPage
public standingsTab = StandingsPage
public testing: any = {id:1, content: 'testing'}
constructor(
public navCtrl: NavController,
public navParams: NavParams) {}
ionViewDidLoad() {
this.team = this.navParams.data
console.log('TeamHomePage navParams.data:')
console.log(this.navParams.data)
console.log('TeamHomePage this.team:')
console.log(this.team)
}
goHome() {
this.navCtrl.popToRoot()
}
}
TeamDetailPage.ts
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { EliteApi } from '../../providers/elite-api/elite-api';
import { GamePage } from '../game/game';
import * as _ from 'lodash'
#Component({
selector: 'page-team-detail',
templateUrl: 'team-detail.html',
})
export class TeamDetailPage {
public team: any = {}
public games: any[]
private tourneyData: any
constructor(
public navCtrl: NavController,
public navParams: NavParams,
private eliteApi: EliteApi
) {}
ionViewDidLoad() {
this.team = this.navParams.data
this.tourneyData = this.eliteApi.getCurrentTourney()
this.games = _.chain(this.tourneyData.games)
.filter(g => g.team1Id === this.team.id || g.team2Id === this.team.id)
.map(g => {
let isTeam1 = (g.teamId === this.team.id)
let opponentName = isTeam1 ? g.team2: g.team1
let scoreDisplay = this.getScoreDisplay(isTeam1, g.team1Score, g.team2Score)
return {
gameId: g.id,
opponent: opponentName,
time: Date.parse(g.time),
location: g.location,
locationUrl: g.locationUrl,
scoreDisplay: scoreDisplay,
homeAway: (isTeam1 ? "vs.": "at")
}
})
.value()
console.log('TeamDetail team:')
console.log(this.navParams.data)
console.log('TeamDetail: tourneyData')
console.log(this.tourneyData)
console.log('TeamDetail touerneyData.games:')
console.log(this.tourneyData.games)
}
getScoreDisplay(isTeam1, team1Score, team2Score) {
if (team1Score && team2Score) {
var teamScore = (isTeam1 ? team1Score : team2Score)
var opponentScore = (isTeam1 ? team2Score : team1Score)
var winIndicator = teamScore > opponentScore ? 'W: ' : 'L: '
return winIndicator + teamScore + '-' + opponentScore
}else {
return ''
}
}
Empty Team Object showing in console chrome

IONIC 2 - Cannot retrieve array inside ionViewDidLoad()

I want to retrieve places coordinates from restApi and display them on the map.
I got error : Cannot read property 'length' of undefined
Please help me !
I want you to tell me how i can get my data in order to add multiple markers.
This is my portion of code
import { Component, ViewChild, ElementRef } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Geolocation } from '#ionic-native/geolocation';
import { RestProvider } from '../../providers/rest/rest';
declare var google;
#Component({
selector: 'page-localisation',
templateUrl: 'localisation.html',
})
export class LocalisationPage {
#ViewChild('map') mapElement: ElementRef;
map: any;
places: Array<any>;
errorMessage : string;
constructor(public navCtrl: NavController, public navParams: NavParams, public geolocation: Geolocation, public rest: RestProvider) {
}
ionViewDidLoad(){
this.loadMap();
this.getPlaces();
this.addPlacesToMap()
console.log("Length : " + this.places.length) ; //Error Cannot read property 'length' of undefined
}
getPlaces() {
this.rest.getPlaces().subscribe(
places => this.places = places,
error => this.errorMessage = <any>error
);
}
loadMap(){
let latLng = new google.maps.LatLng(-4.066548, 5.356315);
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
}
addPlacesToMap(){
//...
}
addInfoWindow(marker, content){
let infoWindow = new google.maps.InfoWindow({
});
content: content
google.maps.event.addListener(marker, 'click', () => {
infoWindow.open(this.map, marker);
});
}
}
ionViewDidLoad is launched before "this.rest.getPlaces().subscribe" is finished... So your variable "places" is NULL
Change getPlaces to a Promise
async getPlaces() {
places = await this.rest.getPlaces() ;
return places
}
Then in ionViewDidLoad
ionViewDidLoad(){
var that = this ;
this.loadMap();
this.getPlaces().then((places)=>{
that.places = places;
console.log("Length : " + that.places.length) ;
});
this.addPlacesToMap()
}

Ionic-3 error Cannot read property 'style' of null

Im Used Ionic-3 and Im hide Tabs bar On Specific pages, Its working fine but i have some issue, some time display this error message
TypeError: Cannot read property 'style' of null
how to fix this issue,
this is my code
check.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams} from 'ionic-angular';
#IonicPage()
#Component({
selector: 'page-check',
templateUrl: 'check.html',
})
export class CheckPage {
tabBarElement: any; // hidetab
constructor(public navCtrl: NavController, public navParams: NavParams) {
this.tabBarElement = document.querySelector('.tabbar.show-tabbar');// hidetab
}
ionViewDidLoad() {
console.log('ionViewDidLoad CheckPage');
}
ionViewWillEnter() {
this.tabBarElement.style.display = 'none'; // hidetab
}
ionViewWillLeave() {
this.tabBarElement.style.display = 'flex'; // hidetab
}
takeMeBack() {
this.navCtrl.parent.select(0); // backbutton
}
}
Try this maybe it can fix your issue :
ionViewWillEnter() {
let tabBarElement = document.querySelector('.tabbar.show-tabbar');
if (tabBarElement != null) {
tabBarElement.style.display = 'none'; // or whichever property which you want to access
}
}

Make a Select-List with Database Data - Ionic 3

I'm having trouble making a select-list with data from the database.
I followed some internet tutorials, but to no avail.
If someone can post an example or point out what I am wrong.
I will be very grateful, therefore, I must do when loading page 3 Select-lists.
auth_pagto.ts
empresa(user) {
//user.sidBanco = "bda1";
var headers = new Headers();
headers.append('Content-Type', 'application/json; charset=utf-8');
return new Promise(resolve => {
this.http.post('/itpowerbr-api/login/empresa', JSON.stringify(user), {headers: headers}).subscribe(data => {
console.log("ENTROU");
var mostraEmpresa: any[];
//lista das empresas
data.json().each(data, function(i, x){
//mostraEmpresa += '<ion-option value="'+ x.empresaNome +'" >'+ x.empresaID +' - '+ x.empresaNome +'</ion-option>';
//{description: "Fazer compras", priority: "7", horary: "22:20"},
this.mostraEmpresa = [
{description: x.empresaNome, priority: x.empresaID}
];
});
//$("#pgt-lista-filial").html(mostraEmpresa);
resolve(mostraEmpresa);
}, (err) => {
if ( err.status == 500 ){
var alert = this.alertCtrl.create({
title: "Pagamentos",
subTitle: "Lista Empresa não Encontrada",
buttons: ['ok']
});
alert.present();
resolve(false);
}else{
var alert = this.alertCtrl.create({
title: "Pagamentos",
subTitle: err,
buttons: ['ok']
});
alert.present();
resolve(false);
}
});
});
}// fim
pagamento.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams, AlertController, LoadingController } from 'ionic-angular';
import { Auth_Pgto } from './auth_pgto';
import { AuthService } from '../login/authservice';
import { Storage } from '#ionic/storage';
import { LoginPage } from '../login/login';
#IonicPage()
#Component({
selector: 'page-pagamentos',
templateUrl: 'pagamentos.html',
})
export class PagamentosPage {
usercreds = {
//nomeUsuario: '',
//token: ''
};
private _lista: any;
constructor(public navCtrl: NavController, public storage: Storage, public navParams: NavParams, public authservice: AuthService, public auth_pgto: Auth_Pgto, public alertCtrl: AlertController, public loadingCtrl: LoadingController) {
var usuario = new Object();
usuario = {
nomeUsuario: window.localStorage.getItem('usuario'),
token: window.localStorage.getItem('raja')
};
this.auth_pgto.empresa(usuario).then(data => {
this._lista = data;
});
}// fim
logout() {
this.authservice.logout();
this.navCtrl.setRoot(LoginPage);
}
public event = {
month: '2017-07-01',
timeStarts: '07:43',
timeEnds: '1990-02-20'
}
ionViewDidLoad() {
console.log('ionViewDidLoad PagamentosPage');
}
}
pagamentos.html
<ion-content padding>
<ion-list> <!-- LISTA EMPRESA -->
<ion-item *ngFor="#_lista of _lista">
<ion-label>Empresa</ion-label>
{{lista.description}}
</ion-item>
</ion-list>
</ion-content>
thank you so much.
I think you are missing the let keyword in your ngFor directive.
<ion-item *ngFor="let item of _lista">