getting data from firebase database by userId - firebase

I'm trying to get data from my database firebase, but I get no data to show in list item html because I pushed UserId first in database.
items: Observable<any[]>;
itemsRef: AngularFireList<any>;
constructor(,public fire: AngularFireAuth,public db: AngularFireDatabase)
{
this.itemsRef = db.list('report/');
// Use snapshotChanges().map() to store the key
this.items = this.itemsRef.snapshotChanges().pipe(
map(changes =>
changes.map(c => ({ key: c.payload.key, ...c.payload.val() }))
)
);
}
you can see here no data to show in list item
html
<ion-list *ngFor="let item of items | async">
<ion-item-sliding>
<ion-item>
<h2>{{item.title}}</h2>
<p>{{item.name}}</p>
<p>{{item.username}}</p>
<p>{{item.dateadded}}</p>
</ion-item>
<ion-item-options side="right">
<button ion-button color="danger" (click)="deletReport(item.key)">
<ion-icon ios="ios-trash" md="md-trash" item-end large></ion-icon>
</button>
<button ion-button color="primary" (click)="updatereport(item.key,item.name,item.title)">
<ion-icon ios="ios-create" md="md-create"></ion-icon>
</button>
</ion-item-options>
</ion-item-sliding>
</ion-list>

Related

Delete data from Firebase Database

Hello I wanted to delete record from the realtime firebase database.I have got the key which I wanted to delete, but when I call remove function on reference is shows me error "Reference.remove failed: first argument must be a valid function."
i had refer this docs.
here is my code:
home-customer.ts
deleteLoad(load) {
this.AuthProvider.removeNote(load.key).then(() => {
this.navCtrl.setRoot('HomeCustomerPage');
});
}
home-customer.html
<ion-list *ngFor="let load of LoadMaster">
<ion-item>
Source:
{{load.Source}}
</ion-item>
<ion-item>
Destination:
{{load.Destination}}
</ion-item>
<ion-item>
Load Type:
{{load.LoadType}}
</ion-item>
<button ion-button block (click)="UpdateLoad(load.key)">
Update
</button>
<button ion-button block (click)="deleteLoad(load)">
Delete
auth.ts
removeNote(key) {
console.log('key'+key);
return firebase.database().ref(`/LoadMaster/`).remove(key);
}
It's very sad since more then 3 year no answer...I think this answer will now help to others...
`var adaRef = firebase.database().ref('users/ada');
adaRef.remove()
.then(function() {
console.log("Remove succeeded.")
})
.catch(function(error) {
console.log("Remove failed: " + error.message)
});`
More can be found Firebase documentation

How to receive data from firebase according to selected option?

I developing an ionic 2 app where people can add their blood types to firebase.
Now I want to implement a search-page to receive that data from firebase, For instance, somebody wants to search for B Rh+ blood type, simply selects that radio button and when they click search I want to search B Rh+ bloods in Firebase and list them.
here is my search html:
<ion-list>
<ion-item>
<ion-label>Blood Type</ion-label>
<ion-select [(ngModel)]="bloodtype">
<ion-option value="ap">A Rh+</ion-option>
<ion-option value="an">A Rh-</ion-option>
<ion-option value="bp">B Rh+</ion-option>
<ion-option value="bn">B Rh-</ion-option>
<ion-option value="abp">AB Rh+</ion-option>
<ion-option value="abn">AB Rh-</ion-option>
<ion-option value="zp">0 Rh+</ion-option>
<ion-option value="zn">0 Rh-</ion-option>
</ion-select>
</ion-item>
<ion-item>
<ion-range [(ngModel)]="range">
<ion-icon range-left small name>0km</ion-icon>
<ion-icon range-right small name>100km</ion-icon>
</ion-range>
</ion-item>
<button ion-button full icon-left (click)="presentLoading()">
<ion-icon name="search"></ion-icon>
Search
</button>
</ion-list>
and here is my search.ts:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { LoadingController } from 'ionic-angular';
#Component({
selector: 'page-search',
templateUrl: 'search.html'
})
export class SearchPage {
constructor(public navCtrl: NavController,public loadingCtrl: LoadingController) {}
ionViewDidLoad() {
console.log('Hello SearchPage Page');
}
presentLoading() {
let loader = this.loadingCtrl.create({
content: "Please wait...",
duration: 3000
});
loader.present();
}
}
I tried to use search bar and receive data with this reference this.bloodRef = firebase.database().ref('/bloods'); but using search bar is not functional since people can type "brh+" or "b" etc.
my firebase hierarchy:
---bloods (id)
------ blood-type: "B Rh+"
You can filter items with orderBy and equalTo functions:
var results = [];
this.bloodRef.orderByChild('blood-type').equalTo(this.bloodtype).once("value")
.then(function(snapshot) {
//snapshot.val() is the object
});

Angularfire2 *ngfor not updating DOM in Ionic 2 app

I'm making a social media app using Ionic with a Firebase backend that I communicate with using Angularfire2.
There's a page in my app that lists all the followers of a user by receiving a uid from the NavParams and sends this to a provider that returns a FirebaseListObservable with that user's followers.
followers-page.ts
constructor(public navCtrl: NavController, public navParams: NavParams, public util: UtilProvider, public userProvider: UserProvider, public socialProvider: SocialProvider, private zone: NgZone) {
this.name = this.navParams.get('name');
this.otherUid = this.navParams.get('uid');
this.currentUid = this.userProvider.currentUid();
}
ionViewDidLoad() {
this.zone.run(() => {
this.users = this.userProvider.getUserFollowers(this.otherUid);
});
}
followers-page.html
<ion-header>
<ion-navbar color='danger'>
<ion-title>{{name}} Followers</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item style="background-color: #fff" *ngIf="!(users | async)">
<ion-avatar item-left>
<img src="assets/img/defaultAvatar.png">
<h2>Loading...</h2>
</ion-avatar>
</ion-item>
<user-item *ngFor="let user of users | async" [user]="user">
</user-item>
</ion-list>
</ion-content>
user-provider.ts
//Get List of followers of uid
getUserFollowers(uid) {
let users = this.af.database.list(`/users/${uid}/followers`, {
query: {
limitToFirst: 10
}
});
return users;
}
user-item.html
<ion-item style="background-color: #fff" text-wrap>
<ion-avatar item-left (click)="userProfile()">
<img [class]="user.visibility > 1 ? 'profile-pic verified' : 'profile-pic'" [src]="user?.avatar ? user.avatar : 'assets/img/defaultAvatar.png'">
</ion-avatar>
<h2 (click)="userProfile(user)">{{user?.name}}</h2>
<button ion-button item-right *ngIf="!(following)" (click)="followUser()">{{user?.followerCount}} Followers</button>
<button ion-button outline item-right icon-left *ngIf="following" (click)="followUser()">
<ion-icon name="checkmark"></ion-icon>Followed
</button>
</ion-item>
Without the limitToFirst query it displays the correct number of followers as user-items but the profile avatar and the name and the follower status are all blank. When I click on the avatar it pushes the correct user-profile page so the data is there but the DOM isn't being updated.
I have this exact same code in the discover tab of my app (without the NgZone) and it works perfectly there.
I tried it without the NgZone here as well but to no avail so I am just about completely lost as to how to get these users' info to display.
Thanks in advance!

Http post request for token based authentication

This is my first application in angular 2 and I am doing jwt authentication for my mobile application,i have problem with HTTP post and i already checked my post Url in Postman it works fine and i got token also. but when i post from client side i got an error. Please get me out.
login.html
<form (ngSubmit)="login()" #loginForm="ngForm">
<ion-list>
<ion-item class="email_border">
<ion-label class="labelstyle"> <ion-icon class="icon" color="dark" ios="ios-person" md="md-person"></ion-icon></ion-label>
<ion-input type="text" placeholder="Email" name="name" [(ngModel)]="name" required></ion-input>
</ion-item>
<div style="font-size:0;height:6px;"></div>
<ion-item class="email_border">
<ion-label class="labelstyle"> <ion-icon class="icon" color="dark" ios="ios-unlock" md="md-unlock"></ion-icon></ion-label>
<ion-input type="password" placeholder="Password" name="Kennwort" [(ngModel)]="Kennwort" required></ion-input>
</ion-item>
</ion-list>
<button icon-left ion-button block type="submit" class="log" [disabled]="!loginForm.form.valid">
<ion-icon style="font-size: 30px" ios="ios-key" md="md-key"></ion-icon> Login </button>
</form>
<button ion-button block clear (click)="register()" class="register"> Register For Free Trail </button>
<button ion-button block clear (click)="resetPwd()" class="fpasswd"> Forgot Password </button>
login.ts
login(name,Kennwort) {
this.auth.loginuser(name,Kennwort).subscribe((result) => {
if (result) {
this.navCtrl.setRoot(HomePage);
}
});
}
authservice.ts
loginuser(name:string, Kennwort:string):Observable<boolean> {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('node.futures-services.com:9000/api/authenticate/', JSON.stringify({ name:name, Kennwort:Kennwort }), { headers:headers })
.map(res => res.json()).map((res) => {
if (res.success) {
localStorage.setItem('token', res.token);
this.loggedIn = true;
}
return res.success;
}).catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}
error look like this error

*ng-for is not rendering DOM but the firebase data is being called

I am getting data from firebase by using the below code and i am able to create an array using the below code.
fetchPeopleFromFirebase(){
Firebase fbUsers = this.fbObject.child("posts");
fbUsers.once("value", (snapshot) => {
if(snapshot.exists()) {
snapshot.forEach((object) => {
console.log("Current Post");
console.log(object.val());
Firebase fbUserDetails = this.fbObject.child("users");
var createdById = object.child('createdBy/_id').val();
console.log("Checking for : " + createdById)
fbUserDetails.child(createdById).once("value", (snapshot) => {
if(snapshot.exists()) {
console.log(snapshot.val());
}
});
this.posts.push(object.val());
});
}
console.log("firebase Data",this.posts);
}
}
I am storing the data in this.posts and i am trying to use it in the view like :
*ng-for="#post of posts"
But it does not display anything while data is being printed on the console
can anyone help me?
EDIT:
<ion-content>
<ion-card *ng-for="#post of posts">
<ion-item>
<ion-avatar item-left>
<img src="{{post.createdBy.avatarUrl}}">
</ion-avatar>
<h2>{{post.createdBy.firstName}} {{post.createdBy.lastName}}</h2>
<p>{{post.createdBy.profession}}</p>
</ion-item>
<ion-item>
<ion-list-header>{{post.title}}</ion-list-header>
<img src="{{post.image}}">
</ion-item>
<ion-card-content>
<p>{{post.description}}.</p>
</ion-card-content>
<ion-item actions class="demo-card">
<button primary clear item-left (click)="openLikesFollowers()">
<icon thumbs-up></icon>
<div>5 followers</div>
</button>
<button primary clear item-left (click)="openLikesFollowers()">
<icon text></icon>
<div>4 Comments</div>
</button>
<p item-left class="time-ago">
61 views
</p>
</ion-item>
<ion-item actions>
<p item-left class="time-ago">
+5 collegues are following this
</p>
</ion-item>
</ion-card>
</ion-content>

Resources