ionic2 facebook login not success - facebook

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) });
}

Related

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();
}

react-native fbsdk is returning email undefined

I m trying to get information through the facebook sdk but so far I am getting only the id and the name of the user. I do have granted the premission but still the email is not popping out like name and id.
I try to console.log(result.email) but i got undefined .
Any help would be appreciated.
Thanks in advance
import React, { Component } from 'react';
import { View } from 'react-native';
import { LoginButton, AccessToken ,GraphRequest, GraphRequestManager} from 'react-native-fbsdk';
export default class Login extends Component {
render() {
return (
<View>
<LoginButton
onLoginFinished={
(error, result) => {
if (error) {
alert("login has error: " + result.error);
} else if (result.isCancelled) {
alert("login is cancelled.");
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
let accessToken = data.accessToken
alert(accessToken.toString())
const responseInfoCallback = (error, result) => {
if (error) {
console.log(error)
alert('Error fetching data: ' + error.toString());
} else {
console.log(result)
console.log(result.email)
alert('Success fetching data: ' + result.toString());
}
}
const infoRequest = new GraphRequest(
'/me',
{
accessToken: accessToken,
parameters: {
fields: {
string: 'name,email'
}
}
},
responseInfoCallback
);
// Start the graph request.
new GraphRequestManager().addRequest(infoRequest).start()
}
)
}
}
}
onLogoutFinished={() => alert("logout.")}/>
</View>
);
}
}

navigation control in ionic provider

Im using navigation control in ionic provider whenever i triggered the provider it shows the runtime error Cannot read property 'pop' of null
my code is
#Injectable()
export class ServerResponseProvider {
#ViewChild('myContent') navCtrl: NavController;
constructor(public http: Http, public alertCtrl: AlertController,
protected injector: Injector, private app:App) {
console.log('Hello ServerResponseProvider Provider');
}
httpGetRes(url) {
return Observable.create(observer => {
this.http.get(url)
.map(res => res.json())
.subscribe(data => {
console.log("response:", data);
observer.next(data);
}, (err) => {
console.log("Your error : ", err);
observer.error(err);
if (err.status == 400) {
this.alertC('Validation Error');
} else if (err.status == 403) {
this.alertC('Authorization error')
} else if (err.status == 500) {
this.alertC('Something went wrong try again later')
}
});
});
}
alertC(msg) {
let alert = this.alertCtrl.create({
title: ' OOPS !!!!',
subTitle: msg,
buttons: [{
text: 'ok',
handler: () => {
this.navCtrl.pop();
}
}]
});
alert.present(alert);
}
}
i tried in many ways it wont works
thanks in advance

Ionic - Unexpected token. A constructor, method, accessor, or property was expected

I want to do news sharing function in my ionic2 apps, and I get this code from ionic document but still showing error.
This is qq sharing, sharing with news text, image, audio, and I also want to know is it ionic got shareSdk like MOB can derictly share with all platform, bcz I have to develop fb, weibo, wechat too. Too many coding
news.ts
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { NewsDataProvider } from '../../providers/news-data/news-data';
import { QQSDK, QQShareOptions } from '#ionic-native/qqsdk';
#Component({
selector: 'page-news-detail',
templateUrl: 'news-detail.html',
})
export class NewsDetailPage {
new: any;
constructor(public navCtrl: NavController,
public navParams: NavParams,
public newsData:NewsDataProvider,
private qq: QQSDK) {
this.new = navParams.get('new');
}
share(){
this.qq.shareText(shareTextOptions)
.then(() => {
console.log('shareText success');
})
.catch(error => {
console.log(error);
});
this.qq.shareImage(options)
.then(() => {
console.log('shareImage success');
})
.catch(error => {
console.log(error);
});
}
this.qq.shareNews(options)
.then(() => {
console.log('shareNews success');
})
.catch(error => {
console.log(error);
});
}
this.qq.shareAudio(options)
.then(() => {
console.log('shareAudio success');
})
.catch(error => {
console.log(error);
});
}
}
Here is the error in my terminal

Login with Facebook and Ionic 3 - Does not take me parameters to the other screen

Does not take me parameters to the other screen
I am trying to get name and email, but it is not running, so the login runs me perfect.
I hope they can help me
The ionic version is as follows:
cli packages: (C:\node\Ionic\taxilurin\node_modules)
#ionic/cli-plugin-cordova : 1.6.2
#ionic/cli-plugin-ionic-angular : 1.4.1
#ionic/cli-utils : 1.7.0
ionic (Ionic CLI) : 3.7.0
global packages:
Cordova CLI : 7.0.1
local packages:
#ionic/app-scripts : 2.1.3
Cordova Platforms : android 6.2.3 browser 4.1.0
Ionic Framework : ionic-angular 3.6.0
System:
Node : v6.11.2
OS : Windows 10
npm : 3.10.10
My code Home - Login:
import { Component } from '#angular/core';
//Importamos los elementos que vamos a utlizar
import { RegistroCPage } from './../RegistroCorpotativo/registroC';
import { RegistroPPage } from './../registroParticular/registroP';
import { RegistroNPage } from './../registroNuevo/registroN';
import { NativeStorage } from '#ionic-native/native-storage';
import { Facebook } from '#ionic-native/facebook';
import { NavController } from 'ionic-angular';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
registroCPage = RegistroCPage;
registroPPage = RegistroPPage;
registroNPage = RegistroNPage;
constructor(
private facebook: Facebook,
public navCtrl: NavController,
public nativeStorage: NativeStorage
) {
}
loginFacebook() {
this.facebook.login(['public_profile', 'email'])
.then(rta => {
console.log(rta.status);
if (rta.status == 'connected') {
this.getInfo();
};
})
.catch(error => {
console.error(error);
});
}
getInfo() {
let nav = this.navCtrl;
let env = this;
this.facebook.api('/me?fields=id,name,email,first_name,picture,last_name,gender', ['public_profile', 'email'])
.then(function (user) {
env.nativeStorage.setItem('user',
{
name: user.name,
gender: user.gender,
picture: user.picture
})
.then(function () {
nav.push(RegistroNPage);
}, function (error) {
console.log(error);
})
})
.catch(error => {
console.error(error);
});
}
}
My code de PostLogen:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { NativeStorage } from '#ionic-native/native-storage';
import { Facebook } from '#ionic-native/facebook';
import { HomePage } from './../home/home';
#Component({
selector: 'page-registroN',
templateUrl: 'registroN.html'
})
export class RegistroNPage {
user: any;
userReady: boolean = false;
constructor(
public navCtrl: NavController,
public fb: Facebook,
public nativeStorage: NativeStorage) {
}
ionViewCanEnter() {
let env = this;
this.nativeStorage.getItem('user')
.then(function (data) {
env.user = {
name: data.name,
gender: data.gender,
email: data.email,
picture: data.picture
};
env.userReady = true;
}, function (error) {
console.log(error);
});
}
doFbLogout() {
var nav = this.navCtrl;
let env = this;
this.fb.logout()
.then(function (response) {
//user logged out so we will remove him from the NativeStorage
env.nativeStorage.remove('user');
nav.push(HomePage);
}, function (error) {
console.log(error);
});
}
}
ionViewCanEnter() method evaluates if router should push page into navigation stack or not. This method should return a boolean (or a Promise of boolean) to do this evaluation.
You actually did not returning a value, so that function is returning undefined and evaluate always as false, so Page can not be entered.
Make this small changes to code to return proper value:
ionViewCanEnter() {
let env = this;
return this.nativeStorage.getItem('user')
.then(function (data) {
env.user = {
name: data.name,
gender: data.gender,
email: data.email,
picture: data.picture
};
env.userReady = true;
return true;
}, function (error) {
console.log(error);
return false;
});
}