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)
));
}
}
Related
I have a BeforeInsert and AfterInsert hook that is not being called. All it does is log hook. I am using nestjs-graphql.
You can run this example doing npm i, then sending a mutation (playground is at localhost:3000/graphql) with body createUser(createInput:{password:"password" email:"test#test.com"}). It should succeed and log hook.
The hook (nothing is logged):
#Entity('user')
export default class UserEntity {
#PrimaryGeneratedColumn()
id: number;
#Column()
#IsEmail()
email: string;
#Column()
#Length(7, 42)
password: string;
#BeforeInsert()
#AfterInsert()
async validate() {
console.log("hook")
}
}
It's called from a service. The insertion does not throw an error, and here2 is logged:
#Injectable()
export class UserService {
constructor(
#InjectRepository(UserEntity)
private readonly userRepository: Repository<UserEntity>,
) { }
async createNew(email: string, password: string): Promise<number> {
console.log("here2")
const hashedPassword = "test"
const res = await this.userRepository.insert({ email, password: hashedPassword })
return res.identifiers[0].id
}
}
According to TypeORM's Docs the listener hooks get called before or after their respective operation when using the entity manager or repository's save method. As insert and similar operations don't call save, they don't execute the #Before/After* methods
#Injectable()
export class UserService {
constructor(
#InjectRepository(UserEntity)
private readonly userRepository: Repository<UserEntity>,
) { }
async createNew(email: string, password: string): Promise<number> {
const res = await this.userRepository.insert(Object.assign(new userRepository(), { email, password: hashedPassword }))
return res
}
}
Try like this
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 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'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);
})
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);
})