I'm using ionic 3 with firebase.
Until now I use angularfire 4.0 and the following code gave me an observable for the data from firebase:
obsToData: FirebaseObjectObservable<any>;
constructor(public nav: NavController, public shared: SharedProvider,
public DB: AngularFireDatabase) {
this.obsToData = DB.object('/myData');
}
now, according to this page FirebaseObjectObservable removed and I need to use AngularFireObject instead, how can I get the data?
I did the following change:
obsToData: AngularFireObject<any>;
constructor(public nav: NavController, public shared: SharedProvider,
public DB: AngularFireDatabase) {
this.obsToData = DB.object('/myData');
}
but I don't find the way how to get an observable from this new object to my data from firebase.
Does someone succeed to use angularfire 5.0?
you need to use valueChanges() to get the Observable from the AngularFireDatabase Object reference.
obsRef: AngularFireObject<any>;
obsToData: Observable<any>;
constructor(public nav: NavController, public shared: SharedProvider,
public DB: AngularFireDatabase) {
this.obsRef = DB.object('/myData');//reference
this.obsToData = this.obsRef.valueChanges();//Observable
}
EDIT to get data and save it,subscribe like any observable
this.obsToData.subscribe(data=>{
console.log(data);
},error=>{
console.log(error);
})
Related
I am integrating Nestjs with firebase admin, the controller is not updating the view. With the service there is not problem, update in real time.
Someone will have some suggestion, what is my wrong in the code?
The Service that inject the controller is:
import { Injectable } from '#nestjs/common';
import * as admin from 'firebase-admin';
export interface Customer {
direction: string,
codLegal: string,
phone: string,
name: string
}
export interface CustomerId extends Customer{
id: string;
}
#Injectable()
export class CustomerService {
constructor() {}
findCustomers(): Promise<any>{
return new Promise((resolve, reject) => {
admin.firestore().collection('/data/LYvBew5FDpjLqcQjA2Ra/info')
.onSnapshot((querySnapshot) => {
const promises: any = [];
querySnapshot.forEach((doc: any) => {
promises.push({
id: doc.id,
data: doc.data() as Customer,
});
});
console.log(promises);
resolve(promises);
})
});
}
}
**The basic controller is: **
import { Controller, Get } from '#nestjs/common';
import { CustomerService } from './services/customer.service';
#Controller('customers') export class CustomerController {
constructor(private readonly customerService: CustomerService) {
}
#Get()
async findAll() {
try {
return await this.customerService.findCustomers();
}catch(err) {
console.log(err);
}
}
}
Talking in terms of HTTP, the controller will not update the view. The view is rendered once you call the findAll route and send to the client.
If you want to show updates to the view in realtime, you should include firebase into your frontend.
I am unable to read data from Firebase using angularfireobject.
This is my code:
export class UserService {
user: Observable<any>;
constructor(private db: AngularFireDatabase) {
}
public getUser($userId: string){
this.db.object('users/'+$userId).valueChanges();
}
}
and in user.component.html
<h1>Welcome {{ (userService.user | async)?.name }}!</h1>
userService.user | json gives null.
Any help is appreciated.
You're not setting your .user Observable anywhere that I see and .getUser() is never called.
If you intend to show information on the current user you'll have to pull in authentication too:
export class UserService {
user: Observable<any>;
constructor(private db: AngularFireDatabase, private auth: AngularFireAuth) {
this.user = auth.user.pipe(switchMap(user =>
user ? db.object(`users/${user.uid}`).valueChanges() : of(null)
));
}
}
I have a simple app set up in Ionic 3 with a login page and a home page. I check to see if the user is logged in, then redirect to either the login page or the home page. That part seems to work.
After the login, on the home page I am trying to get the current logged in user. I get the user twice, and then it returns null twice. Why is the user not persistent? According the the AngularFire docs, the login should be persistent by default.
app.component.ts:
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage:any;
constructor(private afAuth: AngularFireAuth, platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
const authObserver = this.afAuth.authState.subscribe(user =>{
if (user){
this.rootPage = 'HomePage';
authObserver.unsubscribe();
} else {
this.rootPage = 'LoginPage'
authObserver.unsubscribe();
}
});
});
}
}
login.ts:
export class LoginPage {
user = {} as User;
constructor(public authData: AuthProvider, public navCtrl: NavController, public navParams: NavParams) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad LoginPage');
}
login(user: User){
this.authData.loginUser(user.email, user.password).then( authData => {
this.navCtrl.setRoot('HomePage');
}, error => {
console.log('Something went wrong')
});
}
}
home.ts:
export class HomePage {
constructor(private afAuth: AngularFireAuth, public authData: AuthProvider, public navCtrl: NavController, public navParams: NavParams) {
this.afAuth.auth.onAuthStateChanged(user => {
console.log(user);
});
}
}
logs:
login.ts:27 ionViewDidLoad LoginPage
home.ts:22 Hk {D: Array(0), G: "XIzaSyDn9pRx23NeEaCNVMQ0sBveDxYEsGrGvRA", s: "[DEFAULT]", A: "pigs-n-bulls-xxxxxxxx.firebaseapp.com", b: xh, …}
home.ts:22 Hk {D: Array(0), G: "XIzaSyDn9pRx23NeEaCNVMQ0sBveDxYEsGrGvRA", s: "[DEFAULT]", A: "pigs-n-bulls-xxxxxxxx.firebaseapp.com", b: xh, …}
home.ts:27 ionViewDidLoad HomePage
home.ts:22 null
home.ts:22 null
this.afAuth.auth.auth.setPersistence(firebase.auth.Auth.Persistence.LOCAL);
or
this.afAuth.auth.auth.setPersistence(firebase.auth.Auth.Persistence.SESSION);
Then in your auth check code:
this.afAuth.auth.auth.onAuthStateChanged(user => {
if (!user) {
}
}
Take not I am using Angularfire, but accessing the Firebase auth functions directly.
I am searching google all day for this problem. I understand why it is not working, but i can't find any solution or other way to get it work. I need to get it working.
I have made my own API that is correctly working when I surf to the url I get a JSON document with values. But now I got the problem with Ionic Asynchronous and Synchronous problems.
Api Service
import { Injectable } from "#angular/core";
import { HttpClient } from "#angular/common/http";
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
#Injectable()
export class ApiService {
constructor(private _http: HttpClient) { }
public getUserById(id: string)
{
return this._http.get(`mysite`);
}
profile.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { ApiService} from '../../services/ApiService';
#IonicPage()
#Component({
selector: 'page-profile',
templateUrl: 'profile.html',
})
export class Profile{
user : any;
constructor(public navCtrl: NavController, public navParams: NavParams, private api : ApiService) {
}
ionViewDidLoad() {
this.api.getUserById('test').subscribe(data => {
this.user = data;
console.log(this.user);
});
console.log(this.user);
console.log('ionViewDidLoad ProfilePage');
}
}
you see two console.log(this.user), one inside the subscribe (this ons is working I see my JSON in the console). the second one outside the subscribe (this one gives a error undifined).
After searching on google I found this article that explains why it is not working. But I can't find any other solution on how to do it the correct way, because now I can't use {{user.name}} (for example) on my html.
My question is how should I work around this or how can you use API with Ionic.
I'm using ionic 3 with firebase.
Until now I use angularfire 4.0 and the following code gave me an observable for the data from firebase:
obsToData: FirebaseObjectObservable<any>;
constructor(public nav: NavController, public shared: SharedProvider,
public DB: AngularFireDatabase) {
this.obsToData = DB.object('/myData');
}
now, according to this page FirebaseObjectObservable removed and I need to use AngularFireObject instead, how can I get the data?
I did the following change:
obsToData: AngularFireObject<any>;
constructor(public nav: NavController, public shared: SharedProvider,
public DB: AngularFireDatabase) {
this.obsToData = DB.object('/myData');
}
but I don't find the way how to get an observable from this new object to my data from firebase.
Does someone succeed to use angularfire 5.0?
you need to use valueChanges() to get the Observable from the AngularFireDatabase Object reference.
obsRef: AngularFireObject<any>;
obsToData: Observable<any>;
constructor(public nav: NavController, public shared: SharedProvider,
public DB: AngularFireDatabase) {
this.obsRef = DB.object('/myData');//reference
this.obsToData = this.obsRef.valueChanges();//Observable
}
EDIT to get data and save it,subscribe like any observable
this.obsToData.subscribe(data=>{
console.log(data);
},error=>{
console.log(error);
})