no valid session found,must call init and login before logout - facebook

I only have login via facebook in my ionic 2 app. I installed cordova pluginfor that with this code
`ionic plugin add cordova-plugin-facebook4 --variable APP_ID="123456789" --variable APP_NAME="myApplication"`
Sometimes I see this message pop up on my app:
no valid session found,must call init and login before logout
and my app crashes. Below is a screenshot:
I have already tried to delete the app and install it again but the issue still persists.
this is my facebook login
Facebook.login(['email']).then( (response) => {
let facebookCredential = firebase.auth.FacebookAuthProvider
.credential(response.authResponse.accessToken);
var that = this;
firebase.auth().signInWithCredential(facebookCredential)
.then((success) => {
that.nav.setRoot(HomePage);
})
.catch((error) => {
console.log("Firebase failure: " + JSON.stringify(error));
});
}).catch((error) => { console.log(error) });
}
get details from facebook
//facebook functions
getDetailsFacebook() {
var that=this;
Facebook.getLoginStatus().then((response)=> {
if (response.status == 'connected') {
Facebook.api('/' + response.authResponse.userID + '?fields=id,name,gender', []).then((response)=> {
//alert(JSON.stringify(response));
that.uid = response.id;
that.name=response.name;
that.photo = "http://graph.facebook.com/"+that.uid+"/picture?type=large";
that.user=new User(that.uid,that.fireUid,that.name, that.photo);
that.profileData.setProfileData(that.user); // to create class for that
//that.profileData.setProfile(that.uid,that.name,that.photo);
//console.log("id:"+this.uid+this.name+this.photo);
}, (error)=> {
alert(error);
})
}
else {
alert('Not Logged in');
}
})
log out function
logOutFacebook(){
Facebook.logout().then((response)=>
{
this.navCtrl.push(LoginPage);
alert(JSON.stringify(response));
},(error)=>{
alert(error);
})
}
home.html
<ion-header>
<ion-navbar color="pinka">
<ion-title></ion-title>
<ion-buttons start (click)="addNote()">
<button ion-button>
<ion-icon name="add-circle"></ion-icon>
</button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content padding class="padiHome">
<ion-avatar>
<img src={{photo}}>
<h1>{{name}}</h1>
</ion-avatar>
<ion-list>
<ion-item-sliding *ngFor="let note of notes">
<ion-item [ngStyle]="{'background-color':'note.color'}">
<h2>{{note.title}}</h2>
<p>{{note.desc}} + {{note.color}}</p>
</ion-item>
<ion-item-options side="left" style="direction:ltr">
<button ion-button="secondary" (click)="update(note.id)">
<ion-icon name="create"></ion-icon>
edit
</button>
<button ion-button="danger" (click)="delete(note.id)">
<ion-icon name="trash"></ion-icon>
delete
</button>
</ion-item-options>
</ion-item-sliding>
</ion-list>
<button ion-button (click)="logOutFacebook()">log Out</button>
</ion-content>
home.ts
import { Component } from '#angular/core';
import { NavController,NavParams,LoadingController,AlertController,ViewController } from 'ionic-angular';
import { Facebook } from 'ionic-native';
//import pages
import {LoginPage} from "../../pages/login/login";
import {User} from '../../models/user'
import { Storage} from '#ionic/storage';
//import provider
import { ProfileData } from '../../providers/profile-data';
import { NotesData } from '../../providers/notes-data';
import firebase from 'firebase'
import {AddNote} from "../add-note/add-note";
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
//facebook user
userProfile: any = null;
uid: any = null;
fireUid:any=null;
name:string=null;
photo: any = null;
user:User=null;
photos:any=null;
currentUser:any=null;
//notes list
notes:any=null;
data:any;
constructor(public navCtrl: NavController, public navParams: NavParams,public profileData:ProfileData,private viewCtrl: ViewController,public notesData:NotesData,private loadingCtrl: LoadingController,private alertCtrl: AlertController,public storage:Storage) {
this.data={};
this.data.title="";
this.data.desc="";
}
ionViewDidLoad() {
console.log("home");
this.fireUid=firebase.auth().currentUser.uid;
this.currentUser=firebase.auth().currentUser;
this.storage.get('photo').then( (value:any) => {
this.photo=value;
});
this.storage.get('name').then( (value:any) => {
this.name=value;
});
//this.getDetailsFacebook();
this.getNotesList();
}
//facebook functions
getDetailsFacebook() {
var that=this;
Facebook.getLoginStatus().then((response)=> {
if (response.status == 'connected') {
Facebook.api('/' + response.authResponse.userID + '?fields=id,name,gender', []).then((response)=> {
//alert(JSON.stringify(response));
that.uid = response.id;
that.name=response.name;
that.photo = "http://graph.facebook.com/"+that.uid+"/picture?type=large";
that.user=new User(that.uid,that.fireUid,that.name, that.photo);
that.profileData.setProfileData(that.user); // to create class for that
//that.profileData.setProfile(that.uid,that.name,that.photo);
//console.log("id:"+this.uid+this.name+this.photo);
}, (error)=> {
alert(error);
})
}
else {
alert('Not Logged in');
}
})
/*this.photo=firebase.database().ref('users/'+this.currentUser+'/photos').on('value',snapshot=>{
var that=this;
that.photonew=snapshot.val().id;
})
*/
}
}
logOutFacebook(){
Facebook.logout().then((response)=>
{
this.navCtrl.push(LoginPage);
alert(JSON.stringify(response));
},(error)=>{
alert(error);
})
}
//notes functions
getNotesList(){
console.log("get event");
var that=this;
this.notesData.getNotesLIst().on('value', snapshot => {
let notesList= [];
snapshot.forEach( snap => {
console.log("id note"+snap.val().id);
notesList.push({
id: snap.val().id,
title: snap.val().title,
desc: snap.val().desc,
color:snap.val().color,
});
});
that.notes = notesList;
});
}
addNotes() {
let prompt = this.alertCtrl.create({
//title: 'הכנס פתק',
cssClass:'noteAlert',
message: "הכנס פתק תיאור",
inputs: [
{
name: 'title',
placeholder: 'כותרת'
},
{
name: 'desc',
placeholder: 'פרטים'
},
],
buttons: [
{
text: 'ביטול',
handler: data => {
console.log('Cancel clicked');
}
},
{
text: 'הוסף',
handler: data => {
this.data.title=data.title;
this.data.desc=data.desc;
//this.notesData.createNote(this.data.title, this.data.desc);
console.log('פתק נשמר');
}
}
]
});
prompt.present();
console.log(this.data.title, this.data.desc);
}
addNote(){
this.navCtrl.push(AddNote);
}
delete(id:number){
}
update(id:number){}
}

Related

Delete by field value [MEAN]

I'm learning MEAN stack. I want to perform CRUD operations and I'm using mongoose. I am following this question on stackoverflow. I want to delete a document by specific value. In my case it is an article with a unique articleid which should get deleted. Unknowingly I'm doing some terrible mistake with params. Please correct me.
Sample document in mongodb.
{
_id: objectId("5d77de7ff5ae9e27bd787bd6"),
articleid:"art5678",
title:"Installing JDK 8 in Ubuntu 18.04 and later",
content:"<h2>Step 1: Add repository</h2><p><strong>$ sudo add-apt-repository pp..."
date:"Tue, 10 Sep 2019 17:33:51 GMT"
contributor:"Tanzeel Mirza",
__v:0
}
article.component.html
<div class="row mt-5">
<div class="col-md-4 mb-3" *ngFor="let article of articles;">
<div class="card text-center">
<div class="card-body">
<h5 class="card-title">{{article.title}}</h5>
<a (click)="onPress(article.articleid)" class="btn btn-danger">Delete</a>
</div>
</div>
</div>
</div>
(click)="onPress(article.articleid") calls a method in ts file.
article.component.ts
import { Component, OnInit } from '#angular/core';
import { ArticleService } from '../article.service';
#Component({
selector: 'app-articles',
templateUrl: './articles.component.html',
styleUrls: ['./articles.component.css']
})
export class ArticlesComponent implements OnInit {
articles = []
constructor(private _articleService: ArticleService) { }
ngOnInit() {
this._articleService.getEvents()
.subscribe(
res => this.articles = res,
err => console.log(err)
)
}
onPress(id) {
this._articleService.deleteArticle()
.subscribe (
data => {
console.log("hello");
}
);
}
}
I have created a service article.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
#Injectable({
providedIn: 'root'
})
export class ArticleService {
private _deleteUrl = "http://localhost:3000/api/delete/:id";
constructor(private http: HttpClient) { }
getAllArticles() {
...
}
deleteArticle(id) {
return this.http.delete<any>(this._deleteUrl);
}
}
And here is my api.js
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Article = require('../models/article');
const dbstring = ...
mongoose.connect(dbstring, { useNewUrlParser: true }, err => {
...
})
router.delete('/delete/:id', (req, res) => {
let articleData=req.params.id;
console.log(articleData); //Output: {}
console.log('on delete url '+articleData); //Output: on delete url undefined
Article.deleteOne({articleid: articleData}, (error, article) => {
if(error) {
console.log(error)
}
else {
if(!article) {
res.status(401).send('Something went wrong')
}
else {
//res.json(article);
}
}
})
})
module.exports = router;
Ok dont write the code for me, but please at least tell me some study material.
Ok. I did more and more research and figured out the problem. Here are the changes.
api.js
router.delete('/delete/:id', (req, res) => {
let articleId=req.params.id;
Article.deleteOne({articleid: articleId}, (error, article) => {
if(error) {
console.log(error)
}
else {
if(!article) {
...
}
else {
...
}
}
})
})
and article.service.ts
private _deleteUrl = "http://localhost:3000/api/delete";
deleteArticle method should be.
deleteArticle(id) {
return this.http.delete<any>(this._deleteUrl+'/'+id);
}

Why not showing liked icon when page refresh in ionic

I am making like and dislike functionality in ionic app when user like then want to show heart icon and when user dislike then want to show empty heart icon.When like the post then icon show but when refreshing page then its show icon of empty likes.Please help me how to resolve this problem in ionic....
tab1.page.html
<div>
<img src="{{getImage.image}}" (click)="tapPhotoLike(getImage.id)" (click)="toggleIcon(getImage.id)">
</div>
<p no-margin no-padding>
<button clear ion-button icon-only class="like-btn">
<!-- <ion-icon no-padding name="like_btn.icon_name" color="{{ like_btn.color }}" class="icon-space"></ion-icon> -->
<ion-icon name="heart-empty" *ngIf="!iconToggle[getImage.id]" color="{{ like_btn.color }}"></ion-icon>
<ion-icon name="heart" *ngIf="iconToggle[getImage.id]" color="{{ like_btn.color }}"></ion-icon>
</button>
</p>
tab1.page.ts
import { Component, OnInit } from '#angular/core';
import { UserService } from '../user.service';
import { User } from '../user';
import { first } from 'rxjs/operators';
import { Storage } from '#ionic/storage';
import { ToastController } from '#ionic/angular';
import { LoadingController, NavController } from '#ionic/angular';
#Component({
selector: 'app-tab1',
templateUrl: 'tab1.page.html',
styleUrls: ['tab1.page.scss']
})
export class Tab1Page implements OnInit {
num
getImages: User[] = [];
getImages2: User[] = [];
getImages3 = [];
getcounts;
countLikes
counts
unlikes
likesID
iconToggle = [];
like_btn = {
color: 'danger',
icon_name: 'heart-empty'
};
public tap: number = 0;
public status: false;
constructor(private userService: UserService,
public toastController: ToastController,
private storage: Storage,
public navCtrl: NavController,
public loadingController: LoadingController) {
}
doRefresh(event) {
this.userPost();
setTimeout(() => {
event.target.complete();
}, 2000);
}
ngOnInit() {
this.userPost();
//this.getCountOfLikes();
}
async userPost() {
const loading = await this.loadingController.create({
message: 'Please wait...',
spinner: 'crescent',
duration: 2000
});
await loading.present();
this.userService.getUserPost().pipe(first()).subscribe(getImages => {
this.getImages3 = getImages;
loading.dismiss();
});
}
likeButton() {
const detail_id = this.userService.getCurrentIdpostId();
this.storage.get('userId').then((val) => {
if (val) {
let user_id = val
this.userService.userPostLikes(user_id, detail_id).pipe(first()).subscribe(
async data => {
this.iconToggle[this.num] = true;
if (data['status'] === 'you have already liked this post') {
const toast = await this.toastController.create({
message: 'you have already liked this post before.',
duration: 2000
});
toast.present();
}
this.userPost();
}
);
}
});
}
tapPhotoLike($detail_id, num) {
this.userService.setCurrentIdpostId($detail_id);
this.tap++;
setTimeout(() => {
if (this.tap == 1) {
this.tap = 0;
//this.unlikePost();
} if (this.tap > 1) {
this.tap = 0;
}
}, 250);
}
setIconToggles() {
let x = 0;
this.getImages3.forEach(() => {
this.iconToggle[x] = false;
x++;
});
}
toggleIcon(num) {
if (this.iconToggle[num]) {
this.iconToggle[num] = false;
this.unlikePost();
} else {
this.iconToggle[num] = true;
this.likeButton();
}
}
ionViewWillEnter() {
this.userPost();
}
unlikePost() {
let detail_id = this.userService.getCurrentIdpostId();
this.storage.get('userId').then((val) => {
if (val) {
let user_id = val;
this.userService.unLikes(user_id, detail_id).subscribe(async dislikes => {
this.unlikes = dislikes;
this.iconToggle[this.num] = false;
this.userPost();
})
}
});
}
}
How manage icon , i am inserting status on like and dislike in database..In this code how to manage status please help me.

displaying a message in angular 6

hello I'm learning angular 6 but I don't understand why it doesn't display my message but he appears in the logs of my server.
component:
import { Component } from '#angular/core';
import { ChatService } from '../chat.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
message: string;
messages: string[] = [];
constructor(private chatService: ChatService) {
}
sendMessage() {
this.chatService.sendMessage(this.message);
this.message = '';
}
OnInit() {
this.chatService
.getMessages()
.subscribe((message: string) => {
this.messages.push(message);
});
}
}
html:
<div>
<li *ngFor="let message of messages">
{{message}}
</li>
</div>
<input [(ngModel)]="message" (keyup)="$event.keyCode == 13 && sendMessage()" />
<button (click)="sendMessage()">Send</button>
thanks for your help
chat service :
import * a io from 'socket.io-client';
import {Observable} from 'rxjs';
export class ChatService{
private url = 'http://localhost:3000';
private socket;
constructor() {
this.socket = io(this.url);
}
public sendMessage(message){
this.socket.emit('new-message',message);
}
public getMessage = () => {
return Observable.create((observer) => {
this.socket.on('new-message' , (message) => {
observer.next(message);
});
});
}
}

Menu items not appearing programmatically ionic 3 when user signs in. (AWS Cognito)

I am building an ionic app using AWS as a backend (has been challenging!), and for some reason on my user sign-in page, I got this nasty bug that wasn't there when I was using firebase as the backend. In a nutshell, my side menu has items that should appear based on whether the user is logged in or not. If the user is logged in, the menu should have a logout item. If the user is not logged in, the menu should either not have any options, or a redundant sign-in option.
I got the hard part down, which was setting up AWS Cognito to work the sign-in logic, and setting the correct root page, however, after a user logs in, the menu does not show the logout option.
Funny thing, if I reload the app, the menu does show the logout option. Not sure why. Also weird, after I reload the app and I click the logout button, the correct options for a user that is not logged in do appear in the menu. If someone can take a look and tell me why the menu options only render correctly when I log out and if I log in only after I reload the app, I would be very grateful! Thank you in advance for your time! Code below...
app.component.ts:
import { Component } from '#angular/core';
import { Platform, NavController, MenuController } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { TabsPage } from '../pages/tabs/tabs';
import { SignInPage } from '../pages/sign-in/sign-in';
import { AuthService } from '../services/auth';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage: any;
isLoggedIn //this variable holds the status of the user and determines the menu items;
constructor(platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen,
private menuCtrl: MenuController,
private authService: AuthService) {
this.verifyUserstate(); //method to check if a user is logged in
console.log(this.isLoggedIn); //debug line
console.log(this.menuCtrl.get()); //debug line
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();
});
}
onLoad(page: any) {
console.log("onLoad");
this.nav.setRoot(page);
this.menuCtrl.close();
}
onLogout() {
this.authService.logout();
this.verifyUserstate();
this.menuCtrl.close();
}
verifyUserstate() {
console.log("in verify userstate");
this.authService.isAuthenticated()
.then(() => {
this.isLoggedIn = true; //if a user is logged in = true
this.rootPage = TabsPage;
console.log(this.isLoggedIn); // more debug
})
.catch((error) => {
this.isLoggedIn = false; //if user is not logged in = false
this.rootPage = SignInPage;
console.log(this.isLoggedIn); //more debug
});
}
}
app.html:
<ion-menu [content]="nav">
<ion-header>
<ion-toolbar>
<ion-title>Menu</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<button ion-item icon-left (click)="onLoad(signinPage)" *ngIf="!isLoggedIn"> <!-- check isLoggin-->
<ion-icon name="log-in"></ion-icon>
Sign In
</button>
<button ion-item icon-left (click)="onLogout()" *ngIf="isLoggedIn">
<ion-icon name="log-out"></ion-icon>
Log Out
</button>
</ion-list>
</ion-content>
auth.ts:
import { Injectable } from "#angular/core";
import { AlertController } from "ionic-angular";
import { CognitoUserPool, AuthenticationDetails, CognitoUser, CognitoUserSession } from "amazon-cognito-identity-js";
const POOL_DATA = {
UserPoolId: "xx-xxxx-X_XXXX",
ClientId: "You do not need to know :)"
}
const userPool = new CognitoUserPool(POOL_DATA);
export class AuthService {
signin(email: string, password: string) {
let message: string;
var authenticationData = {
Username : email,
Password : password,
};
var authDetails = new AuthenticationDetails(authenticationData);
let userData = {
Username: email,
Pool: userPool
}
let cognitoUser = new CognitoUser(userData);
return new Promise((resolve, reject) => {
cognitoUser.authenticateUser(authDetails, {
onSuccess(result: CognitoUserSession) {
console.log(result)
resolve("Success!")
},
onFailure(error) {
let message: string = error.message;
reject(message);
}
}
logout() {
this.getAuthenticatedUser().signOut();
}
isAuthenticated() {
return new Promise((resolve, reject) => {
let user = this.getAuthenticatedUser();
if (user) {
user.getSession((err, session) => {
if(session.isValid()) {
resolve(true);
} else if (err) {
reject(err.message);
}
})
} else {
reject("Not authenticated");
}
});
}
}
Finally, the sign-in.ts file (where the magic of login in happens):
import { Component } from '#angular/core';
import { NgForm } from '#angular/forms';
import { LoadingController, AlertController } from 'ionic-angular';
import { AuthService } from '../../services/auth';
import { NavController } from 'ionic-angular/navigation/nav-controller';
import { MyApp } from '../../app/app.component';
#Component({
selector: 'page-sign-in',
templateUrl: 'sign-in.html',
})
export class SignInPage {
constructor(private authService: AuthService,
private loadingCtrl: LoadingController,
private alertCtrl: AlertController,
private navCtrl: NavController) {
}
onSignin(form: NgForm) {
const loading = this.loadingCtrl.create({
content: "Signing you in..."
});
loading.present();
this.authService.signin(form.value.email, form.value.password)
.then(data => {
this.navCtrl.setRoot(MyApp); /*navigate to myApp again to reverify the
*login status. This sets the right rootPage,
*but I have a feeling here also lies the menu problem.
*/
console.log(data);
})
.catch(error => {
console.log(error);
let alert = this.alertCtrl.create({
title: "Oops",
message: error,
buttons: ["Ok"]
});
alert.present();
})
loading.dismiss();
}
}

Make a Select-List with Database Data - Ionic 3

I'm having trouble making a select-list with data from the database.
I followed some internet tutorials, but to no avail.
If someone can post an example or point out what I am wrong.
I will be very grateful, therefore, I must do when loading page 3 Select-lists.
auth_pagto.ts
empresa(user) {
//user.sidBanco = "bda1";
var headers = new Headers();
headers.append('Content-Type', 'application/json; charset=utf-8');
return new Promise(resolve => {
this.http.post('/itpowerbr-api/login/empresa', JSON.stringify(user), {headers: headers}).subscribe(data => {
console.log("ENTROU");
var mostraEmpresa: any[];
//lista das empresas
data.json().each(data, function(i, x){
//mostraEmpresa += '<ion-option value="'+ x.empresaNome +'" >'+ x.empresaID +' - '+ x.empresaNome +'</ion-option>';
//{description: "Fazer compras", priority: "7", horary: "22:20"},
this.mostraEmpresa = [
{description: x.empresaNome, priority: x.empresaID}
];
});
//$("#pgt-lista-filial").html(mostraEmpresa);
resolve(mostraEmpresa);
}, (err) => {
if ( err.status == 500 ){
var alert = this.alertCtrl.create({
title: "Pagamentos",
subTitle: "Lista Empresa não Encontrada",
buttons: ['ok']
});
alert.present();
resolve(false);
}else{
var alert = this.alertCtrl.create({
title: "Pagamentos",
subTitle: err,
buttons: ['ok']
});
alert.present();
resolve(false);
}
});
});
}// fim
pagamento.ts
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams, AlertController, LoadingController } from 'ionic-angular';
import { Auth_Pgto } from './auth_pgto';
import { AuthService } from '../login/authservice';
import { Storage } from '#ionic/storage';
import { LoginPage } from '../login/login';
#IonicPage()
#Component({
selector: 'page-pagamentos',
templateUrl: 'pagamentos.html',
})
export class PagamentosPage {
usercreds = {
//nomeUsuario: '',
//token: ''
};
private _lista: any;
constructor(public navCtrl: NavController, public storage: Storage, public navParams: NavParams, public authservice: AuthService, public auth_pgto: Auth_Pgto, public alertCtrl: AlertController, public loadingCtrl: LoadingController) {
var usuario = new Object();
usuario = {
nomeUsuario: window.localStorage.getItem('usuario'),
token: window.localStorage.getItem('raja')
};
this.auth_pgto.empresa(usuario).then(data => {
this._lista = data;
});
}// fim
logout() {
this.authservice.logout();
this.navCtrl.setRoot(LoginPage);
}
public event = {
month: '2017-07-01',
timeStarts: '07:43',
timeEnds: '1990-02-20'
}
ionViewDidLoad() {
console.log('ionViewDidLoad PagamentosPage');
}
}
pagamentos.html
<ion-content padding>
<ion-list> <!-- LISTA EMPRESA -->
<ion-item *ngFor="#_lista of _lista">
<ion-label>Empresa</ion-label>
{{lista.description}}
</ion-item>
</ion-list>
</ion-content>
thank you so much.
I think you are missing the let keyword in your ngFor directive.
<ion-item *ngFor="let item of _lista">