Ionic 3 firebase display data error - firebase

Currently I am able to post data to the firebase, but I can't get the data and display it in my ionic 3 app. This is my shoes.ts file:
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { AngularFireDatabase } from "angularfire2/database";
import { FirebaseListObservable } from 'angularfire2/database';
#Component({
selector: 'page-shoes',
templateUrl: 'shoes.html',
})
export class ShoesPage {
shoppingItems: FirebaseListObservable<any[]>;
newItem = '';
getShoppingItems() {
return this.afDB.list('/shoppingItems/');
}
constructor(public navCtrl: NavController, public navParams: NavParams,
public afDB: AngularFireDatabase){
this.addItem("awesomeStuff");
this.getShoppingItems();
alert(this.shoppingItems);
}
ionViewDidLoad() {
console.log('ionViewDidLoad ShoesPage');
}
addItem(name) {
this.afDB.list('/shoppingItems/').push(name);
}
removeItem(id) {
this.afDB.list('/shoppingItems/').remove(id);
}
}
This is a part of my the shoes.html file:
<ion-list>
<ion-item class="text" *ngFor="let item of shoppingItems | async">
{{item.$value}}
</ion-item>
</ion-list>
Any ideas how I can be able to display the firebase data? Currently I am getting: [object Object] when I alert the shoppingList.

Related

Routing edit/id in asp.net core application with angular not working

I am learning building application using angular and asp.net core using these videos on this link. Everything works fine except the edit of a component. If I give a URL like below, it goes to the route for error in app-routing.module.ts even though there's no error in the browser console log.
http://localhost:4200/genres/edit/1
The app-routing.model.ts is as below
import { Component, NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { CreateActorComponent } from './actors/create-actor/create-actor.component';
import { EditActorComponent } from './actors/edit-actor/edit-actor.component';
import { IndexActorsComponent } from './actors/index-actors/index-actors.component';
import { CreateGenreComponent } from './genres/create-genre/create-genre.component';
import { EditGenreComponent } from './genres/edit-genre/edit-genre.component';
import { IndexGenresComponent } from './genres/index-genres/index-genres.component';
import { HomeComponent } from './home/home.component';
import { CreateMovieTheaterComponent } from './movie-theaters/create-movie-theater/create-movie-theater.component';
import { EditMovieTheaterComponent } from './movie-theaters/edit-movie-theater/edit-movie-theater.component';
import { IndexMovieTheaterComponent } from './movie-theaters/index-movie-theater/index-movie-theater.component';
import { CreateMovieComponent } from './movies/create-movie/create-movie.component';
import { EditMovieComponent } from './movies/edit-movie/edit-movie.component';
const routes: Routes = [
{path:' ', component:HomeComponent},
{path:'genres', component:IndexGenresComponent},
{path:'genres/create', component:CreateGenreComponent},
{path:'genres/edit:id', component:EditGenreComponent},
{path:'actors', component:IndexActorsComponent},
{path:'actors/create', component:CreateActorComponent},
{path:'actors/edit:id', component:EditActorComponent},
{path:'movietheaters', component:IndexMovieTheaterComponent},
{path:'movietheaters/create', component:CreateMovieTheaterComponent},
{path:'movietheaters/edit:id', component:EditMovieTheaterComponent},
{path:'movies/create', component:CreateMovieComponent},
{path:'movies/edit:id', component:EditMovieComponent},
// {path:'**',component:HomeComponent}
{path:'**',redirectTo:' '}
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
edit-genre.component.ts is
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { genreCreationDTO } from '../genres.model';
#Component({
selector: 'app-edit-genre',
templateUrl: './edit-genre.component.html',
styleUrls: ['./edit-genre.component.css']
})
export class EditGenreComponent implements OnInit {
constructor(private activatedRoute:ActivatedRoute) { }
model: genreCreationDTO={name:"Drama"};
ngOnInit(): void {
this.activatedRoute.params.subscribe(params=>{
});
}
//Event emiited value passed from child form-genre-creation to parent create-genre.component
//to be displayed
saveChanges(genreCreationDTO:genreCreationDTO)
{
}
}
edit-genre.component.html is
<h2>Edit Genre</h2>
<app-form-genre [model]="model" (onSaveChanges)="saveChanges($event)"></app-form-genre>
form-genre.component.html is
<form (submit)="saveChanges()" [formGroup]="form">
<mat-form-field appearance="outline">
<mat-label>Name*</mat-label>
<input matInput formControlName="name">
<mat-error *ngIf="form.invalid">{{getErrorMessageFieldName()}}</mat-error>
</mat-form-field>
<div>
<button mat-flat-button color="primary" [disabled]="form.invalid">Save Changes</button>
<a mat-stroked-button routerLink="/genres">Cancel</a>
</div>
form-genre.component.ts is
import { Component, OnInit, Output,EventEmitter, Input } from '#angular/core';
import { FormBuilder, FormGroup, Validators } from '#angular/forms';
import { Router } from '#angular/router';
import { firstLetterUppercase } from 'src/app/validators/firstLetterUppercase';
import { genreCreationDTO } from '../genres.model';
#Component({
selector: 'app-form-genre',
templateUrl: './form-genre.component.html',
styleUrls: ['./form-genre.component.css']
})
export class FormGenreComponent implements OnInit {
constructor(private router: Router, private formBuilder:FormBuilder) { }
#Input()
model!: genreCreationDTO;
//Event Emitter
#Output()
onSaveChanges: EventEmitter<genreCreationDTO>=new EventEmitter<genreCreationDTO>();
form!: FormGroup;
ngOnInit(): void {
this.form= this.formBuilder.group({
name:['',[Validators.required, Validators.minLength(3),firstLetterUppercase()]]
});
if(this.model!==undefined){
this.form.patchValue(this.model);
}
}
getErrorMessageFieldName()
{
const field= this.form.get("name");
if(field?.hasError("required"))
{
return "The name field is required";
}
if(field?.hasError("minLength")){
return "The minimum length is 3"
}
if(field?.hasError('firstLetterUppercase')){
return field.getError('firstLetterUppercase').message;
}
return '';
}
saveChanges()
{
//Emit value from child form-genre.compnent to parent create-genre.component
this.onSaveChanges.emit(this.form.value);
// this.router.navigate(['/genres']);
}
}
I am new to .net core framework & angular and i'm using forms(chapter sharing forms) in the video tutorial by Felipe galivan. Everytime I give an edit/id url for a component, it keeps using this
{path:'**',redirectTo:' '}
in the app-routing.module.ts as if say genres/edit/id has no match. I'm doing exactly as Felipe in the video, mine keeps redirecting me to home page instead of genres/edit. Why is this happening?

adding firebase to Ionic 3

I'm trying to add firebase to ionic 3 but I'm getting an error on Object (...) not a function, everything runs well until the subscribe function gets executed then the error shows, I've done all needed integration and here my home.ts code
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { FirstPage } from '../first/first';
import { AskPage } from '../ask/ask';
import {AngularFireDatabase} from 'angularfire2/database'
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController,
public afd : AngularFireDatabase) {
this.getDataFromFireBase();
}
getDataFromFireBase(){
this.afd.list('/Heros/').valueChanges().subscribe(
data => {
console.log(JSON.stringify(data))
}
)
}

Data from firebase don't load?

I am trying to get data of a certain userId out of a firebase Database. But nothing happens? I am creating an AngularFireObject of typ Profile
like this:
profileData: AngularFireObject<Profile>;
There is no error in the code. the HTML is shown how i prefer it but without the data.
the only thing what isn't correct, is that the Methode ionViewDidLoad is shown as unused. But when i pass the code inside the constructor it doesn't has any effect.
Can someone help me with that? Thanks a lot!
import { Component } from '#angular/core';
import {IonicPage, NavController, NavParams, ToastController} from 'ionic-angular';
import {AngularFireAuth} from 'angularfire2/auth';
import {AngularFireDatabase, AngularFireObject} from 'angularfire2/database';
import {Profile} from '../../shared/models/profile';
/**
* Generated class for the HomePage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
#IonicPage()
#Component({
selector: 'page-home',
templateUrl: 'home.html',
})
export class HomePage {
profileData: AngularFireObject<Profile>;
constructor(private afAuth: AngularFireAuth, private afDatabase: AngularFireDatabase, private toast: ToastController,
public navCtrl: NavController, public navParams: NavParams) { }
ionViewDidLoad() {
this.afAuth.authState.subscribe(data => {
console.log(data.uid);
if (data && data.email && data.uid) {
console.log(data.email);
console.log(data.uid);
this.toast.create({
message: `Welcome to The APP, ${data.email}`,
duration: 5000
}).present();
this.profileData = this.afDatabase.object(`/profile/${data.uid}`)
console.log(this.profileData);
} else {
this.toast.create({
message: `Could not find authentication details`,
duration: 3000
}).present();
}
})
}
}
This is the HTML where i would like to load the data.
profile.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {AngularFireAuth} from 'angularfire2/auth';
import {Profile} from '../../shared/models/profile';
import {AngularFireDatabase} from 'angularfire2/database';
#IonicPage()
#Component({
selector: 'page-profile',
templateUrl: 'profile.html',
})
export class ProfilePage {
profile = {} as Profile;
constructor(private afAuth: AngularFireAuth, private afDatabase: AngularFireDatabase,
public navCtrl: NavController, public navParams: NavParams) {
}
/*ionViewDidLoad() {
console.log('ionViewDidLoad ProfilePage');
}*/
createProfile(){
this.afAuth.authState.take(1).subscribe(auth => {
this.afDatabase.object(`profile/${auth.uid}`).set(this.profile)
.then(() => this.navCtrl.setRoot('HomePage'))
})
}
}
<p>Username: {{(profile | async)?.username }}</p>
<p>First Name: {{(profile | async) ?.lastName }}</p>
<p>Last Name: {{(profile | async) ?.firstName}}</p>
There is a issue in the path. your path has a userid which concatenated with profile without separating it using slash (/)
Try to re correct path,
this.afDatabase.object(`/profile/${data.uid}`)
To retrieve data and view, do this way
this.afAuth.authState.subscribe(data => {
if (data && data.email && data.uid) {
this.afDatabase.database.ref().child(`/profile/${data.uid}`).once('value', (snapshot) => {
let result = snapshot.val();
for (let k in result) {
this.profileData = result[k];
}
});
}
});
**This is the html **
<p>Username: {{ profileData.username }}</p>
<p>First Name: {{ profileData.lastName }}</p>
<p>Last Name: {{( profileData.firstName}}</p>
in Homepage.ts
you only have to add take(1) in ligne 27 just like that :
this.afAuth.authState.take(1).subscribe(data => {

TypeError: Cannot read property 'propName' of null

I always get this error:
TypeError: Cannot read property 'propName' of null
Here is my Typescript.
handlu-prop.ts
import { Component } from '#angular/core';
import { IonicPage, ModalController, NavController, NavParams, ActionSheetController } from 'ionic-angular';
import { AlertController } from 'ionic-angular';
import { AngularFireDatabase,FirebaseObjectObservable } from 'angularfire2/database';
import { Subscription } from 'rxjs/Subscription';
import { ConAgentsPage } from '../conagents/conagents';
import { HandluPage } from '../handlu/handlu';
import { PropertyItem } from '../../models/property-item/PropItem.interface';
#IonicPage()
#Component({
selector: 'page-handlu-prop',
templateUrl: 'handlu-prop.html',
})
export class HandluPropPage {
propertyItemSubscription: Subscription;
propertyItem = {} as PropertyItem;
propertyItemRef$: FirebaseObjectObservable<PropertyItem>;
constructor(private database: AngularFireDatabase,
private modCtrl: ModalController,
public navCtrl: NavController,
public navParams: NavParams,
public alertCtrl: AlertController) {
const propertyItemId = this.navParams.get('$key');
console.log(propertyItemId);
this.propertyItemRef$ = this.database.object(`Property/${propertyItemId}`).valueChanges();
this.propertyItemSubscription =
this.propertyItemRef$.subscribe( propertyItem => this.propertyItem = propertyItem );
}
ionViewWillLeave() {
this.propertyItemSubscription.unsubscribe();
}
handlu-prop.html (here is a part of my template)
<h2>{{propertyItem.propName}}</h2>
Try modifying your HTML file to this
<h2>{{ propertyItem?.propName }}</h2>
the ? serves the purpose of checking if this element is defined or not, it avoids crashing the app into that error.

Property 'login' does not exist on type 'AngularFireAuth' ionic

Iam trying to create a login page using firebase in ionic.I have imported al the neccessary componenets but i get the error Property 'login' does not exist on type 'AngularFireAuth' in the login method. Please help!
login.ts
import { Component } from '#angular/core';
import { NavController, NavParams, AlertController, LoadingController, Loading, IonicPage } from 'ionic-angular';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { AngularFireAuth } from 'angularfire2/auth';
#Component({
selector:'page-login',
templateUrl:'login.html'
})
export class LoginPage{
email: any;
password: any;
constructor(public NavCtrl: NavController,public NavParams,public angfire: AngularFireAuth){
}
ionViewDidLoad(){
console.log('ionViewDidload LoginPage');
}
login(){
this.angfire.login({
email:this.angfire,
password:this.password
},
})
}
}
For AngularFire2 try this
signInWithFacebook() {
this.afAuth.auth.signInWithPopup(new firebase.auth.FacebookAuthProvider())
.then(res => console.log(res));
}

Resources