Want to fetch data from firestore to my ionic 4 app - ionic-framework

I was able to upload some data to my firestore account, but i can't fetch or read the data. I'm new and will appreciate if i am guided like a newbie.
ngOnInit() {
this.bookingservice.read_AcBookings().then(data =>
this.booking = data.map(e => {
return {
id: e.payload.doc.id,
isEdit: false,
// tslint:disable-next-line: no-string-literal
firstname: e.payload.doc.data()['firstname'],
// tslint:disable-next-line: no-string-literal
lastname: e.payload.doc.data()['lastname'],
// tslint:disable-next-line: no-string-literal
phonenumber: e.payload.doc.data()['phonenumber'],
// tslint:disable-next-line: no-string-literal
address: e.payload.doc.data()['address'],
// tslint:disable-next-line: no-string-literal
location: e.payload.doc.data()['location'],
// tslint:disable-next-line: no-string-literal
date: e.payload.doc.data()['date'],
// tslint:disable-next-line: no-string-literal
servicebooked: e.payload.doc.data()['servicebooked'],
};
}));
console.log(this.booking);
}
This is the service
read_AppliancesBookings() {
return new Promise<any>((resolve, reject) => {
this.afAuth.user.subscribe(currentUser => {
if (currentUser) {
this.snapshotChangesSubscription = this.firestore.collection('Bookings').doc(currentUser.uid).collection('Appliances Bookings')
.snapshotChanges();
resolve(this.snapshotChangesSubscription);
}
});
});
}

There are a few fundamental mistakes in your bookingservice, so I just rewrote it for you. Hopefully you can learn what was wrong by looking at this code.
import { Injectable } from '#angular/core';
import { AngularFireAuth } from '#angular/fire/auth';
import { AngularFirestore } from '#angular/fire/firestore';
import { reject } from 'q';
#Injectable({
providedIn: 'root'
})
export class bookingservice {
constructor(public afAuth: AngularFireAuth, public firestore: AngularFirestore) { }
userId = this.afAuth.auth.currentUser.uid;
read_AppliancesBookings() {
return new Promise((resolve, reject) => {
this.firestore
.doc<any>(`Bookings/${userId}`)
.valueChanges()
.subscribe(doc => {
resolve(doc);
});
}).then((result) => {
return result;
});
}
}
Let me know if that works.

Related

redux-toolkit InitialState not changing

My problem is that initialState from slice.js not changing, when I console.log store(using UseSelector) I see that state.list empty and did not changed.I'm trying to catch data from GET endpoint, endpoint is working.
store.js
import { configureStore } from '#reduxjs/toolkit';
import shopReducer from '../connection/shopSlice';
export const store = configureStore({
reducer: {
shop: shopReducer,
},
devTools: true
});
slice.js
import { createAsyncThunk, createSlice } from '#reduxjs/toolkit';
import axios from 'axios';
export const getProducts = createAsyncThunk(
'shop/getProducts',
async () => {
const response = await axios.get('http://localhost:3000/products');
return response.data;
}
);
export const listOfProducts = createSlice({
name: 'shop',
initialState: {
list: [],
status: 'idle',
error: null,
},
reducers: {
addProduct: {
reducer: (state, action) => {
state.list.push(action.payload);
},
prepare(value) {
return {
payload: {
key: value.id,
value: value,
},
};
},
},
},
extraReducers: {
[getProducts.pending]: (state, action) => {
state.status = 'loading';
},
[getProducts.fulfilled]: (state, action) => {
state.status = 'succeeded';
state.list.push(...action.payload);
},
[getProducts.rejected]: (state, action) => {
state.status = 'failed';
state.error = action.error.message;
},
},
});
export const { addProduct } = listOfProducts.actions;
export default listOfProducts.reducer;
component with console.log
import React from 'react';
import common from './common.module.scss';
import shopCards from './shopCards.module.scss';
import { useSelector } from "react-redux";
const ShopCards = () => {
console.log(useSelector(state=>state))
return (
<div>
</div>
);
};
export default ShopCards;
The issue is that you are not dispatching the getProducts at all, you should dispatch this action and get the state with useSelector(state => state.shop) to select the proper reducer state. Try to change your code to the following:
import React from 'react';
import common from './common.module.scss';
import shopCards from './shopCards.module.scss';
// Don't forget to change the path
import { getProducts } from './path/to/reducer'
import { useSelector, useDispatch } from "react-redux";
import { useEffect } from "react";
const ShopCards = () => {
const products = useSelector((state) => {state.shop});
useEffect(() => {
// dispatch the action on first render
useDispatch(getProducts());
}, []);
useEffect(() => {
// print the products if the fetch to backend was made successfully
console.log(products);
}, [products]);
return (
<div>
</div>
);
};
export default ShopCards;
Other thing, in your createAsyncThunk you are returning response.data, so to fulfill properly the state, your api response should looks like this:
{
// you must return a JSON with data key who has an array of your products
// the content of product was just an example, so ignore it
data: [{id: 1, product: "foo"}]
}

How to push an element to an array in a MongoDB document on Nest.js?

I feel extremely dumb making this question, but it's my first time working with Typescript in general and Nest.js in particular. I'm working with Nest, MongoDB (through Mongoose) and Express.js.
I have two models: User and Post. For this, the relevant one would be the User:
import * as Mongoose from 'mongoose';
export const UserSchema = new Mongoose.Schema(
{
username: { type: String, required: true },
posts: { type: [Mongoose.SchemaTypes.ObjectId], ref: 'Post' },
favs: { type: [Mongoose.SchemaTypes.ObjectId], ref: 'Post' },
},
{
timestamps: true,
},
);
I'm making an API for a Twitter-like app, in which an user can create posts and add them to Favorites. I'm following tutorials, as one does when new to a technology, but I'm struggling to see how to push a new fav to the user's favs. Here's the User controller, so far:
import {
Controller,
Get,
Req,
Res,
HttpStatus,
Put,
NotFoundException,
Param,
} from '#nestjs/common';
import { UserService } from './user.service';
import { Request, Response } from 'express';
import { CreateUserDTO } from './dto/create-user.dto';
#Controller('user')
export class UserController {
constructor(private userService: UserService) {}
//fetch an user
#Get('userfavs/:userID')
async getCustomer(#Res() res: Response, #Param('userID') userID: string) {
const user = await this.userService.getUser(userID);
if (!user) throw new NotFoundException('This user does not exist!');
return res.status(HttpStatus.OK).json({
username: user.username,
favs: user.favs,
});
}
#Put('addfav/:favID')
async updateUser(
#Req() req: Request,
#Res() res: Response,
#Param('favID') favID: string,
#Body() createUserDTO: CreateUserDTO,
) {
const user = await this.userService.updateUser(req.user._id, createUserDTO);
if (!user) throw new NotFoundException('This user does not exist!');
return res.status(HttpStatus.OK).json({
message: 'Fav added successfully!',
});
}
}
And the service:
import { Injectable } from '#nestjs/common';
import { Model } from 'mongoose';
import { InjectModel } from '#nestjs/mongoose';
import { User } from './interfaces/user.interface';
import { CreateUserDTO } from './dto/create-user.dto';
#Injectable()
export class UserService {
//creates Mongoose model for the User
constructor(#InjectModel('User') private readonly userModel: Model<User>) {}
//fetch a specific user - this will be useful to check favs
async getUser(userID: string): Promise<User> {
const user = await this.userModel
.findById(userID)
.populate('favs')
.exec();
return user;
}
//edit an specific user
async updateUser(
userID: string,
createUserDTO: CreateUserDTO,
): Promise<User> {
const updatedUser = await this.userModel.findByIdAndUpdate(
userID,
createUserDTO,
{ new: true },
);
return updatedUser;
}
}
In Node.js I would have done like:
User.findByIdAndUpdate(req.user._id, {
$push: { favs: favId },
})
But in Nest, the DTO is throwing me for a loop.
With NestJS, you can fetch your document from Mongo with a find operation (find, findById, findOne, etc). Then, modify that object, and save. You can pass your favId to your service from your controller instead of the DTO. In your service:
async updateUser(
userID: string,
favId: string
): Promise < User > {
const user = await this.userModel.findById(userID).exec();
if (!user) {
throw new NotFoundException();
}
user.favs.push(favId);
return user.save();
}

Error: Uncaught (in promise): TypeError: Cannot read property 'dismiss' of undefined in ionic 5

I am building an app with ionic 5, i want to show ion-loader when a user tries to login, and after a response is gotten from the server, it will dismiss the ion-loader, but when i tried it, i got this error
Error: Uncaught (in promise): TypeError: Cannot read property 'dismiss' of undefined
here is my code
import { Component, OnInit } from '#angular/core';
import { HomePage } from '../home/home.page';
import { NavController, AlertController, LoadingController } from '#ionic/angular';
import { AuthServiceService } from '../auth-service.service';
#Component({
selector: 'app-login',
templateUrl: './login.page.html',
styleUrls: ['./login.page.scss'],
})
export class LoginPage implements OnInit {
ngOnInit() {
}
registerCredentials = { email: '', password: '' };
loaderToShow: any;
constructor(
public navCtrl: NavController,
private auth: AuthServiceService,
private alertCtrl: AlertController,
private loadingCtrl: LoadingController
) {
console.log(this.registerCredentials);
}
public login() {
this.showLoading();
this.auth.login(this.registerCredentials).subscribe(allowed => {
if (allowed) {
this.loaderToShow.dismiss();
console.log('canceal')
} else {
this.showError('Access Denied');
}
}, error => {
this.showError(error);
});
}
public async showLoading() {
this.loaderToShow = await this.loadingCtrl.create({
message: 'Please Wait...'
});
await this.loaderToShow.present();
}
public async showError(text) {
this.loaderToShow.dismiss();
let alert = await this.alertCtrl.create({
header: 'Fail',
message: text,
buttons: ['OK']
});
await alert.present();
}
}
Pls how can i properly dismiss the ion-loader
Create a hideLoading() method like below can call it when you want to hide the loading circle.
async hideLoading() {
this.loadingController.getTop().then(loader => {
if (loader) {
loader.dismiss();
}
});
}
I created below class to handle show hide of loading in my ionic application.
loading.service.ts
import { Injectable } from '#angular/core';
import { LoadingController } from '#ionic/angular';
#Injectable({
providedIn: 'root'
})
export class LoadingService {
isLoading = false;
constructor(public loadingController: LoadingController) { }
async showLoading(message?: string) {
this.isLoading = true;
this.loadingController.create({
message: message ? message : 'Please wait...'
}).then(loader => {
loader.present().then(() => {
if (!this.isLoading) {
loader.dismiss();
}
});
});
}
async hideLoading() {
this.isLoading = false;
this.loadingController.getTop().then(loader => {
if (loader) {
loader.dismiss();
}
});
}
}
Usage in a component:
export class SomePage implements OnInit {
subscription: Subscription;
constructor(private loadingService: LoadingService) { }
someMethod(updateNameForm: NgForm) {
this.loadingService.showLoading();
this.someService.someMethod().subscribe(response => {
// Some code
});
this.subscription.add(() => {
this.loadingService.hideLoading();
});
}
}
}
The solution is to add await to the call of the function showLoading
public login() {
await this.showLoading();
this.auth.login(this.registerCredentials).subscribe(allowed => {
if (allowed) {
this.loaderToShow.dismiss();
console.log('canceal')`enter code here`
} else {`enter code here`
this.showError('Access Denied');
}
}, error => {
this.showError(error);
});
}
async showLoading() {
this.loaderToShow = await this.loadingCtrl.create({
message: 'Please Wait...'
});
await this.loaderToShow.present();
}
async showError(text) {
await this.loaderToShow.dismiss();
let alert = await this.alertCtrl.create({
header: 'Fail',
message: text,
buttons: ['OK']
});
await alert.present();
}

Loader Appearing continue in ionic ios when login

I am new to ionic development and I am facing some issue
We are consuming an API in the ionic3 app.
When the user enters the credentials for login whether they are valid or invalid it shows the message according to the results from API in android.
But When i enter the wrong credentials in the ios build it will continue shows the loader and not giving the API result.
Following the app.component
import { Component, ViewChild } from '#angular/core';
import { Platform, Events, Nav, AlertController } from 'ionic-angular';
//import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { MenuController } from 'ionic-angular/components/app/menu-controller';
import { StorageService } from '../pages/shared/storage.service';
import { ToastService } from '../pages/shared/toast.service';
import { Network } from '#ionic-native/network';
//import { Observable } from 'rxjs/Observable';
import { UserService } from '../pages/shared/user.service';
import { Push, PushObject, PushOptions } from '#ionic-native/push';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav;
alert: any;
isAlertShown: boolean;
task: any;
rootPage: any = '';
userDetails: any;
showSubmenu: boolean = true; //for open always
constructor(public platform: Platform, public splashScreen: SplashScreen,
public menu: MenuController,
private storage: StorageService, private toast: ToastService, public events: Events,
private push: Push,
private alertCtrl: AlertController, public network: Network, private api: UserService) {
platform.ready().then(() => {
this.userDetails = this.storage.getData('userDetails');
this.isAlertShown = false;
this.task = setInterval(() => {
this.checkInternet();
}, 3000);
this.pushSetup();
if (this.userDetails != undefined || this.userDetails != null) {
this.rootPage = 'welcome';
} else {
this.rootPage = 'login';
}
this.initializeApp();
});
events.subscribe('user:login', (username) => {
// user and time are the same arguments passed in `events.publish(user, time)`
this.getLoggedIn();
});
events.subscribe('user:logout', () => {
this.rootPage = 'login';
});
events.subscribe('root:change', (page) => {
// user and time are the same arguments passed in `events.publish(user, time)`
this.rootPage = page;
});
events.subscribe('user:pic', (userpic) => {
// user and time are the same arguments passed in `events.publish(user, time)`
this.userDetails = this.storage.getData('userDetails');
this.userDetails = {
userId: this.userDetails.userId,
username: this.userDetails.username,
profileUrl: userpic
}
this.storage.saveData('userDetails', this.userDetails);
this.getLoggedPic('pic');
});
}
initializeApp() { //for reduce time of white screen after splash
this.platform.ready().then(() => {
// do whatever you need to do here.
setTimeout(() => {
this.splashScreen.hide();
}, 100);
});
}
checkInternet() {
this.alert = this.alertCtrl.create({
title: 'Disconnected',
message: 'Please connect your device to internet',
buttons: [
{
text: 'Try again',
handler: () => {
this.checkagain();
}
}
], enableBackdropDismiss: false
});
this.api.getCategoryList()
.then(result => {
// console.clear();
if (result.type == 'error') {
if (this.isAlertShown == false) {
this.alert.present();
this.isAlertShown = true;
}
this.storage.saveData('connect', 'offline');
}
else if (result.status == true) {
this.storage.saveData('connect', 'online');
this.alert.dismiss();
}
})
}
public checkagain() {
this.isAlertShown = false;
//this.alert.dismiss();
}
public logout(): void {
this.storage.removeData('userDetails');
this.toast.ShowNotification('Logout Successful', 'bottom');
this.rootPage = 'login';
}
getLoggedPic(page) {
this.userDetails = this.storage.getData('userDetails');
if (page == "pic") {
this.userDetails.profileUrl = this.userDetails.profileUrl + "?" + new Date().getTime();
}
}
getLoggedIn() {
this.userDetails = this.storage.getData('userDetails');
if (this.userDetails != undefined || this.userDetails != null) {
this.rootPage = 'welcome';
this.userDetails = this.storage.getData('userDetails');
this.userDetails.profileUrl = this.userDetails.profileUrl + "?" + new Date().getTime();
} else {
this.rootPage = 'login';
}
}
openMenu(): void {
//Commented for click on edit profile to not collepes
//this.showSubmenu = !this.showSubmenu;
}
openPage(pagename: string) {
this.rootPage = pagename;
//this.nav.push(pagename);
}
openHomePage(pagename: string) {
this.rootPage = pagename;
}
pushSetup() {
console.log("inside pushSetup");
const options: PushOptions = {
android: {
senderID: 'xxxxxxxxxxx
forceShow: 'true'
},
ios: {
alert: 'true',
badge: true,
sound: 'false'
}
};
const pushObject: PushObject = this.push.init(options);
pushObject.on('notification').subscribe((notification: any) => console.log('Received a notification', notification));
pushObject.on('registration').subscribe((registration: any) => this.storage.saveData("token", registration.registrationId));
pushObject.on('error').subscribe(error => console.error('Error with Push plugin', error));
}
}
Following is my login.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, Events, LoadingController } from 'ionic-angular';
import { FormGroup, FormBuilder, Validators } from '#angular/forms';
import { UserLogin } from '../shared/user';
import { UserService } from '../shared/user.service';
import { ToastService } from '../shared/toast.service';
import { StorageService } from '../shared/storage.service';
import { MenuController } from 'ionic-angular/components/app/menu-controller';
import { Platform } from 'ionic-angular';
#IonicPage({
name: 'login'
})
#Component({
selector: 'page-login',
templateUrl: 'login.html',
})
export class LoginPage {
public loginForm: FormGroup;
public submitted: boolean = false;
public userDetails: any;
private isUserLoggin: boolean = false;
private devicetype: any;
unamePattern = "(?:\d{10}|\w+#\w+\.\w{2,3})";
constructor(public nav: NavController, public formBuilder: FormBuilder,public platform: Platform,
private userService: UserService, private toast: ToastService, public loading: LoadingController, private storage: StorageService, private menuCtrl: MenuController,
public events: Events) {
if (this.platform.is('ios')) {
this.devicetype = "ios";
}
else {
this.devicetype = "android";
}
this.menuCtrl.enable(false); // for sidemenu disable
this.nav = nav;
this.isUserLoggin = this.userService.isUserLoggedIn();
this.loginForm = formBuilder.group({
username: ['', Validators.compose([Validators.required])],
password: ['', Validators.compose([Validators.required])]
});
}
// get username() {
// return this.loginForm.get('username');
// }
public save(model: UserLogin, isValid: boolean) {
this.submitted = true;
if (isValid) {
const formData = new FormData();
debugger
formData.append("user_login", model.username);
formData.append("user_password", model.password);
formData.append("device_type",this.devicetype);
formData.append("device_id",""+this.storage.getData("token"));
// console.log("storage id of device ="+this.storage.getData("token"));
let loader = this.loading.create({
content: 'Please wait'
});
loader.present().then(() => {
});
//this.toast.ShowLoaderOnLoad();
try {
this.userService.loginUser(formData)
.then(result => {
loader.dismiss();
if (result.status === true) {
this.userDetails = {
userId: result.data.user_id,
username: result.data.first_name,
profileUrl: result.data.picture_url
}
this.storage.saveData('userDetails', this.userDetails);
this.events.publish('user:login', result.data.first_name); //send an event to menu for show name
this.toast.ShowNotification(result.message, 'bottom');
this.nav.setRoot('welcome');
}
else if (result.status === false) {
this.loginForm = this.formBuilder.group({
username: [model.username, Validators.compose([Validators.required])],
password: ['', Validators.compose([Validators.required])]
});
this.submitted = false;
this.toast.ShowNotification(result.message, 'bottom');
}
else {
this.toast.ShowNotification('Something went wrong!', 'bottom');
this.loginForm.reset();
this.submitted = false;
isValid = false;
}
})
}
catch (error) {
this.loginForm = this.formBuilder.group({
username: [model.username, Validators.compose([Validators.required])],
password: ['', Validators.compose([Validators.required])]
});
this.submitted = false;
this.toast.ShowNotification('Something went wrong!', 'bottom');
}
}
}
ionViewWillEnter() {
if (this.isUserLoggin) {
this.nav.setRoot('welcome');
}
}
public gotoregister() {
this.nav.setRoot('register');
}
public gotoforget() {
this.nav.setRoot('forget');
}
public resetForm() {
this.submitted = false;
}
}
your
loader.present().then(() => {
});
is empty. Which means that your loader.dismiss() might activate before it is instantiated.
Try to put your try block in the call back of the present() function:
try {
etc...}
please Try with this
this.userService.loginUser(formData)
.then((res:any)=>{
//Success Code here
//Stop Loader
}).catch((err:any)=>{
//Error handling and Stop loader
})

ionic2 facebook login not success

i'm trying to do login to my app with facebook,
i installed the cordova facebook plugin
and this my code but i get error on Promise
this is my code(actually i just copied it from tutorial that say it works for him)
import { Component } from '#angular/core';
import { NavController,Platform } from 'ionic-angular';
import {Http, Headers, RequestOptions} from '#angular/http';
import 'rxjs/add/operator/map';
declare const facebookConnectPlugin: any;
#Component({
templateUrl: 'build/pages/home/home.html',
})
export class HomePage {
posts:any;
constructor(public platform: Platform, private navCtrl: NavController,private http: Http)
{ this.platform = platform;
this.http = http;
}
fblogin()
{
this.platform.ready().then(() => {
this.fblogin1().then(success => {
console.log("facebook data===" + success);
alert("facebook data===" + success);
this.http.post('http://localhost/facebook.php',success)
.map( res =>res.json()).subscribe(data => {
if(data.msg=="fail")
{
console.log('Login failed');
alert("Invalid username and password");
return;
}
else
{
console.log(' login Sucessfully facebook');
}
});
}, (error) => {
alert(error);
});
});
}
fblogin1(): Promise<any>
{
return new Promise(function(resolve,reject)
{
facebookConnectPlugin.login(["email"], function(response)
{
alert(JSON.stringify(response.authResponse));
facebookConnectPlugin.api('/' + response.authResponse.userID + '?fields=id,name,email,gender',[],
function onSuccess(result)
{
//alert(JSON.stringify(result));
//console.log(JSON.stringify(result));
resolve(JSON.stringify(result));
},
function onError(error)
{
alert(error);
}
);
},
function(error)
{
alert(error);
})
});
}
}
if anyone know another way i would like to know.
i solve this issue by changing the login function to this code
facebookLogin(){
Facebook.login(['email']).then( (response) => {
let facebookCredential = firebase.auth.FacebookAuthProvider
.credential(response.authResponse.accessToken);
var that = this;
firebase.auth().signInWithCredential(facebookCredential)
.then((success) => {
that.userProfile = JSON.stringify(success);
that.nav.setRoot(HomePage);// after login go to HomePage
})
.catch((error) => {
console.log("Firebase failure: " + JSON.stringify(error));
});
}).catch((error) => { console.log(error) });
}