Use user data logged in with firebase on ionic 4 - android

I am a child with an application with Ionic 4, my application is already logging in with Email, Facebook and Google using Firebase. I created a comments page and the comments are already being saved in Firestore and being displayed on a page. Wow do I get the logged in user data and insert it in this page. Comments?
I used the following solution:
JS:
in the builder
fireAuth.user.subscribe((data => {
this.user = data;
}));
Methods
listarComentarios() {
this.crudService.read_Comentarios().subscribe(data => {
this.comentarios = data.map(e => {
return {
id: e.payload.doc.id,
isEdit: false,
Comentario: e.payload.doc.data()['Comentario'],
Usuario: e.payload.doc.data()['Usuario'],
Foto: e.payload.doc.data()['Foto']
};
})
console.log(this.comentarios);
});
CreateRecord() {
let record = {};
record['Comentario'] = this.comentarioUsuario;
record['Usuario'] = this.user.displayName
record['Foto'] = this.user.photoURL
this.crudService.create_NewComentario(record).then(resp => {
this.comentarioUsuario = "";
this.user.displayName = "";
this.user.photoURL = "";
console.log(resp);
})
.catch(error => {
console.log(error);
});
HTML:
<ion-content>
<ion-grid *ngFor="let item of comentarios">
<span *ngIf="!item.isEdit; else elseBlock">
<!-- this rows will represent sample comments -->
<ion-row class="post-content">
<ion-col size="2" >
<ion-avatar class="ion-align-self-start">
<img class="icon-photo" [src]="item.Foto">
</ion-avatar>
</ion-col>
<ion-col size="6">
<div>
<p><strong>{{item.Usuario}} </strong>{{item.Comentario}}</p>
</div>
</ion-col>
<ion-col>

Related

How can I put a video in ionic with mediaCapture?

In the app I get this error Object: object,
After recording the video when giving it ready to be displayed on the screen I get that error.
VideoPage.HTML
<ion-header>
<ion-toolbar color="primary">
<ion-title>Subir Video</ion-title>
<ion-buttons slot="start">
<ion-back-button defaultHref="/autoventa"></ion-back-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-progress-bar [value]="uploadProgress" color="tertiary"></ion-progress-bar>
<ion-list>
<ion-item-sliding *ngFor="let f of files">
<ion-item (click)="openFile(f)">
<ion-icon name="videocam" slot="start" *ngIf=" f.name.endsWith('mp4')"></ion-icon>
<ion-label class = "ion-text-wrap">
{{ f.name }}
<p> {{ f.fullPath }}</p>
</ion-label>
</ion-item>
<ion-item-options side="start">
<ion-item-option (click)="deleteFile(f)" color="danger">
<ion-icon name="trash" slot="icon-only"></ion-icon>
</ion-item-option>
</ion-item-options>
<ion-item-options side ="end">
<ion-item-option (click)="uploadFile(f)" color = "primary">
<ion-icon name="cloud-upload" slot = "icon-only"></ion-icon>
</ion-item-option>
</ion-item-options>
</ion-item-sliding>
</ion-list>
</ion-content>
<ion-footer>
<ion-toolbar color = "primary">
<ion-button fill="clear" expand="full" color="light" (click)="selectMedia()">
<ion-icon slot = "start" name="document"></ion-icon>
Seleccionar Media
</ion-button>
</ion-toolbar>
</ion-footer>
Declaration of Variables
media folder... I put it before the #component
and files[] before the constructor
const MEDIA_FOLDER_NAME = 'my_media';
files = [];
my recordVideo in videoPage.ts
I use this method to open the camera and record, this part works but at the moment of giving it ready I get an Object object error
recordVideo(){
this.mediaCapture.captureVideo().then(
(data: MediaFile[]) => {
if(data.length > 0 ){
this.copyFileToLocalDir(data[0].fullPath)
}
},
(err: CaptureError) => {
console.log(err)
alert(err);
}
);
}
CopyFile
after recording command to call this method
but I think the error is in this method
copyFileToLocalDir(fullPath){
let myPath = fullPath;
// Make sure we copy from the right location
if (fullPath.indexOf('file://') < 0) {
myPath = 'file://' + fullPath;
}
const ext = myPath.split('.').pop();
const d = Date.now();
const newName = `${d}.${ext}`;
const name = myPath.substr(myPath.lastIndexOf('/') + 1);
const copyFrom = myPath.substr(0, myPath.lastIndexOf('/') + 1);
const copyTo = this.file.dataDirectory + MEDIA_FOLDER_NAME;
this.file.copyFile(copyFrom, name, copyTo, newName).then(
success => {
this.loadFiles();
},
error => {
console.log('error: ', error);
alert(error);
}
);
}
LoadFiles with this method I show the files
loadFiles(){
this.file.listDir(this.file.dataDirectory, MEDIA_FOLDER_NAME).then(
res => {
this.files = res;
},(err)=> {
console.log('Error al cargar archivos: ', err);
alert(err);
}
);
}
ngOnInit
ngOnInit() {
this.plt.ready().then(() =>{
let path = this.file.dataDirectory +MEDIA_FOLDER_NAME;
this.file.checkDir(path, MEDIA_FOLDER_NAME).then(
() => {
this.loadFiles();
},
err => {
this.file.createDir(path, MEDIA_FOLDER_NAME, false);
}
);
});
}

Ionic - App works fine on browser and iOS simulator but not in android simulator

I am really new to the mobile development world and trying my hands on it using IonicFramework.
I am creating a login form and on successful login the user gets take to another state which is called viewMyList. Everything seems to be working fine when I run the command ionic serve I am able to login and proceed to the next state and all seems to be fine on iOS simulator as well but on Android simulator on clicking the login button nothing happens, I don't see any error either.
My attempt
login.html
<ion-view title="Login">
<ion-content class="has-header" padding="true">
<form class="list">
<h2 id="login-heading3" style="color:#000000;text-align:center;">Welcome back!</h2>
<div class="spacer" style="width: 300px; height: 32px;"></div>
<ion-list>
<label class="item item-input">
<span class="input-label">Email</span>
<input type="text" placeholder="" ng-model="credentials.username">
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="text" placeholder="" ng-model="credentials.password">
</label>
</ion-list>
<div class="spacer" style="width: 300px; height: 18px;"></div>
<a class="button button-positive button-block" ng-click="login()">Sign In</a>
</form>
</ion-content>
</ion-view>
ng-click is linked with login()
Here is my loginCtrl which contains the login() function
.controller('loginCtrl', function ($scope, $state, $ionicHistory, User) {
$scope.credentials = {
username: '',
password: ''
};
$scope.login = function () {
User.login($scope.credentials)
.then(function (response) {
console.log(JSON.stringify(response));
//Login should not keep any history
$ionicHistory.nextViewOptions({historyRoot: true});
$state.go('app.viewMyList');
})
};
$scope.message = "this is a message loginCtrl";
})
Here is my User service that takes care of the login logic
angular.module('app.user', [])
.factory('User', function ($http) {
var apiUrl = 'http://127.0.0.1:8000/api';
var loggedIn = false;
return {
login: function (credentials) {
console.log(JSON.stringify('inside login function'));
console.log(JSON.stringify(credentials));
return $http.post(apiUrl + '/tokens', credentials)
.success(function (response) {
console.log(JSON.stringify('inside .then of login function'));
var token = response.data.token;
console.log(JSON.stringify(token));
$http.defaults.headers.common.Authorization = 'Bearer ' + token;
persist(token);
})
.error(function (response) {
console.log('inside error of login function');
console.log(JSON.stringify(response));
})
;
},
isLoggedIn: function () {
if (localStorage.getItem("token") != null) {
return loggedIn = true;
}
}
};
function persist(token) {
window.localStorage['token'] = angular.toJson(token);
}
});
Here is the route behind the login
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'loginCtrl'
})
I am really clueless at the moment as I cant seem to figure out why nothing happens on Android, from my troubleshooting all I could find was when I click on login button the code does not seem to be going inside the following function.
$scope.login = function () {
User.login($scope.credentials)
.then(function (response) {
console.log(JSON.stringify(response));
//Login should not keep any history
$ionicHistory.nextViewOptions({historyRoot: true});
$state.go('app.viewMyList');
})
};
Any help will really be appreciated.
Install whitelist plugin first.
cordova plugin add cordova-plugin-whitelist
add following code in your config.xml file under your root directory of project
<allow-navigation href="http://example.com/*" />
or:
<allow-navigation href="http://*/*" />
If still you are facing any issue, then you can check console while you are running in android device using chrome remote debugging
Connect your device with your machine.(Make sure USB debugging should be enable on your mobile).
write chrome://inspect in browser in your desktop chrome.
you will see connected device, select inspect and check console for log.

how to resolve invalid parameters value for origin

I am trying my mobile application login through google account.
I got this error invalid request and invalid parameter value for origin:missing authority:file://. How to resolve it can any one please help me.
I am trying to checking my application in android mobile i got this below error.
var CLIENT_ID = '349212001841-0o5cf26ah1g7fc4ufsfa1unk0ph3qoab.apps.googleusercontent.com';
var SCOPES = [ 'https://www.googleapis.com/auth/gmail.readonly' ];
function checkAuth() {
gapi.auth.authorize({
'client_id' : CLIENT_ID,
'scope' : SCOPES.join(' '),
'immediate' : true
}, handleAuthResult);
}
function handleAuthResult(authResult) {
alert("success")
var authorizeDiv = document.getElementById('authorize-button');
if (authResult && !authResult.error) {
authorizeDiv.style.display = 'none';
loadGmailApi();
} else {
authorizeDiv.style.display = 'inline';
}
}
function handleAuthClick(event) {
alert("failure")
gapi.auth.authorize({
client_id : CLIENT_ID,
scope : SCOPES,
immediate : false
}, handleAuthResult);
return false;
}
function loadGmailApi() {
gapi.client.load('gmail', 'v1', listLabels);
}
function listLabels() {
var request = gapi.client.gmail.users.labels.list({
'userId' : 'me'
});
request.execute(function(resp) {
var labels = resp.labels;
appendPre('Labels:');
if (labels && labels.length > 0) {
for (i = 0; i < labels.length; i++) {
var label = labels[i];
appendPre(label.name)
}
} else {
appendPre('No Labels found.');
}
});
}
function appendPre(message) {
var pre = document.getElementById('output');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
<div data-role="page" id="loginPage">
<div data-role="content" style="padding: 15px">
<h1 id="fb-welcome"></h1>
<label for="text">User Name:</label><input type="text" name="text" id="unL">
<label for="text">Password:</label><input type="password" name="text" id="pwdL">
LOGIN
via Facebook Login
via Google Login
</div>
</div>
<div data-role="page" id="dashboardPage">
<div data-role="header" id="header" data-position="fixed">
<h3>DashBord</h3>
</div>
<div data-role="content" style="padding: 15px">
<a href="#" data-role="button" onclick='Logout();'>LogOut</a>
</div>
</div>

ng click not calling the function --very new to angular and ionic

trying to insert data to the sqlite db and the data is static that i am passing it through the function but ng click is not working. as i am new to this so please answer in details...thanks in advance.
//this is my module
var db=null;
var myApp=angular.module('starter', ['ionic','ngCordova'])
.run(function($ionicPlatform,$cordovaSQLite) {
$ionicPlatform.ready(function() {
if(window.cordova && window.cordova.plugins.Keyboard) {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
// Don't remove this line unless you know what you are doing. It stops the viewport
// from snapping when text inputs are focused. Ionic handles this internally for
// a much nicer keyboard experience.
cordova.plugins.Keyboard.disableScroll(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
db = $cordovaSQLite.openDB({name:"my.db",location:'default'});
$cordovaSQLite.execute(db,"CREATE TABLE IF NOT EXISTS user(id integer primary key, username text, password text)")
});
})
//this is my controller
myApp.controller('SignInCtrl',['$cordovaSQLite', function($scope, $cordovaSQLite) {
$scope.insert=function(username,password){
alert("hii");
var query="INSERT INTO user(username,password) VALUES(?,?)";
$cordovaSQLite.execute(db.query,[username,password]).then(function(res){
console.log("Insert ID ->" + res.insertId);
},
function(err){
console.error(err);
});
}
$scope.select = function(username) {
var query = "SELECT username, password FROM user WHERE username = ?";
$cordovaSQLite.execute(db, query, [password]).then(function(res) {
if(res.rows.length > 0) {
console.log("SELECTED -> " + res.rows.item(0).username + " " + res.rows.item(0).password);
} else {
console.log("No results found");
}
}, function (err) {
console.error(err);
});
}
}])
//this is my page
<ion view view-title="Sign-In" name="Login-View">
<ion content class="padding">
<div class="list list-inset">
<label class="item item-input">
<input type="text" placeholder="Username" ng-model="data.username">
</label>
<label class="item item-input">
<input type="password" placeholder="Password" ng-model="data.password"></input>
</label>
</div>
</ion>
<button class="button button-block button-positive" ng-click="login(data)">Login</button>
</ion>
<br>
Sign Up
Forgot Password
Order page
<button class="button button-block button-positive" ng-click="insert('ran','badu')">insert</button>
<button class="button button-block button-positive" ng-click="select('ran')">select</button>
//this is my index page
<body ng-app="starter">
<ion-header-bar class="bar-positive">
<h1 class="title">Billing system</h1>
<button class="button icon ion-navicon"></button>
<button class="button icon ion-search"></button>
</ion-header-bar>
<!-- <ion-content > -->
<!-- <P>I am in index</P>
Loginpage -->
<!-- </ion-content> -->
<ion-nav-view class="slide-left-right"></ion-nav-view>
</body>
//this is my route
.config(function($stateProvider,$urlRouterProvider) {
$stateProvider
.state('Login',{
url:'/Login',
templateUrl:'templates/Login.html',
controller:'SignInCtrl'
})
.state('Signup',{
url:'/Signup',
templateUrl:'templates/Signup.html',
controller:'SignInCtrl'
})
.state('ForgotPassword',{
url:'/ForgotPassword',
templateUrl:'templates/ForgotPassword.html',
controller:'SignInCtrl'
})
.state('orderpage',{
url:'/orderpage',
templateUrl:'templates/orderpage.html',
controller:'SignInCtrl'
})
$urlRouterProvider.otherwise('/Login');
})
You have an error with SignInCtrl declaration. Change this line of code
myApp.controller('SignInCtrl',['$cordovaSQLite', function($scope, $cordovaSQLite)
with
myApp.controller('SignInCtrl',['$scope','$cordovaSQLite', function($scope, $cordovaSQLite)
The problem here is that you use inline dependency injection and the order is important
Looking at your code the login() method does not exist in your SignIn controller try adding the login method to the controller
myApp.controller('SignInCtrl', ['$cordovaSQLite', function ($scope, $cordovaSQLite) {
$scope.insert = function (username, password) {
alert("hii");
var query = "INSERT INTO user(username,password) VALUES(?,?)";
$cordovaSQLite.execute(db.query, [username, password]).then(function (res) {
console.log("Insert ID ->" + res.insertId);
},
function (err) {
console.error(err);
});
}
$scope.select = function (username) {
var query = "SELECT username, password FROM user WHERE username = ?";
$cordovaSQLite.execute(db, query, [password]).then(function (res) {
if (res.rows.length > 0) {
console.log("SELECTED -> " + res.rows.item(0).username + " " + res.rows.item(0).password);
} else {
console.log("No results found");
}
}, function (err) {
console.error(err);
});
}
$scope.login = function(data){
//Add Login Logic ....:)
console.log(data)
}
}])

Phonegap Can't Redirecting to a page

So I have this form where upon submission I do a SQL query and redirect it to another page. But when I try to test this on the android tablet it doesnt redirect, nor does it error meaning the SQL call is valid and works...can someone please help me out
<div class="wrapper">
<div class="oneSection">
<form method="post" action="" id="barcodeForm">
Barcode: <br/>
<input name="barcode" id="barcode" type="text" class="sub"/><br/>
<input type="submit" class="open" id="before" value="SUBMIT" onclick="check()" />
</form>
</div>
</div>
<script type="text/javascript">
function check() {
var barcode = $('#barcode').val();
if(barcode.length <= 0) {
$('#barcode').css('border', '2px solid red');
e.preventDefault();
return;
} else {
alert(barcode.length);
var barcode = $('#barcode').val();
checkBarcode(false, barcode);
}
}
function checkBarcode(doAuto, id) {
var successCall;
if (doAuto) {
successCall = function (tx, result) {
var item = result.rows.item(0);
$('[name="client"]').val(item['cname']);
$('[name="address"]').val(item['address']);
$('[name="sitename"]').val(item['sname']);
$('[name="model"]').val(item['model']);
$('[name="lasttested"]').val(item['ltest']);
$('[name="nounits"]').val(item['units']);
$('[name="comments"]').val(item['comments']);
}
} else {
test.innerHTML += 'at the start<br/>';
successCall = function () {
var URL = 'test.html?id=' + id;
window.location.href = URL;
}
}
var queryDB = function queryDB(tx) {
tx.executeSql(getBarcode, [id], successCall, onError);
}
db.transaction(queryDB, onError);
}
</script>
What happens at the moment is that it submit's the input value and resets the form without forwarding the page or anything...

Categories

Resources