refresh app.components in ionic 3 - ionic-framework

i want refresh app.component because in my sidemenu there is image and name so i store name and image in local storage but when i login and go to dashboard my app.component not refresh so need refresh app.components
My menu file
<ion-menu [content]="content">
<ion-header>
<ion-toolbar>
<ion-title>Menu</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<div class="profile">
<img class="profile-picture" src="assets/imgs/user_profile.png" />
<h3 class="name">{{name}}</h3>
</div>
<ion-list class="bg-color-menu" no-lines>
<ion-item menuClose ion-item *ngFor="let p of pages" (click)="openPage(p)">
<ion-item>
<ion-avatar item-start>
<img [src]="p.icon" />
</ion-avatar>
{{p.title}}
</ion-item>
</ion-item>
</ion-list>
</ion-content>
</ion-menu>
<!-- Disable swipe-to-go-back because it's poor UX to combine STGB with side menus -->
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>
app.components
name:any;
this.name = localStorage.getItem("name");

Make your user data as BehaviorSubject.
Add a service - user.service.ts
export class UserService {
private currentUserSub = new BehaviorSubject<User>(null);
constructor(
private http: HttpClient
) {
const user = JSON.parse(localStorage.getItem('user'));
this.currentUserSub.next(user);
}
login(loginData): Observable<User> {
return this.http.post('login', loginData)
.map((res: any) => res.data)
.do((user: User) => {
localStorage.setItem('user', JSON.stringify(user));
this.currentUserSub.next(user);
});
}
getCurrentUserDetails(): Observable<User> {
const user = JSON.parse(localStorage.getItem('user'));
this.currentUserSub.next(user);
return this.currentUserSub;
}
}
call getCurrentUserDetails in app.component.ts to get the current user data
getUserDetails() {
this.userService.getCurrentUserDetails().subscribe(res => {
this.userProfile = res;
});
}
In app.html
<div class="profile">
<img class="profile-picture" src="userProfile.imgUrl" />
<h3 class="name">{{userProfile.name}}</h3>
</div>
this is an example. Do it as per your requirement.

Related

How to pass data to another page from Input Form in IONIC 5

I have an input form with 3 text input. The only thing i want it is to send this 3 datas to another page that i called "Identity". I'd like to know how can do to send this 3 datas to another page using ionic 5. I want to create a signing step by step style. someone can help please?
REGISTER.PAGE.HTML
<ion-content fullscreen="true" class="background-contact">
<div class="fixed">
<div class="div-3">
<div align="center">
<b>IDENTIFICATION</b>
</div>
<ion-label position="stacked" class="title">E-mail</ion-label>
<div align="center" class="input-class">
<ion-input autofocus="true" ngModel name="email" type="email" placeholder="informez votre email"></ion-input>
</div>
<div class="line">
<ion-label position="stacked" class="title">Mot de passe</ion-label>
<div align="center" class="input-class">
<ion-input ngModel name="password" type="password" placeholder="informez votre mot de passe"></ion-input>
</div>
</div>
<!-- <div class="line">
<ion-label position="stacked" class="title">Téléphone</ion-label>
<div align="center" class="input-class">
<ion-input autofocus="true" ngModel name="phone" type="text" placeholder="Tapez votre numéro de tel" (keypress)="numberOnlyValidation($event)"></ion-input>
</div>
</div> -->
<div class="line">
<ion-label position="stacked" class="title">Pays</ion-label>
<div align="center" >
<ion-select cancelText="Fermer" okText="Confirmer" ngModel name="cod_country">
<ion-select-option value="">Dans quel pays êtes-vous?</ion-select-option>
<ion-select-option value="{{item?.id}}" *ngFor="let item of country">{{item?.name}}</ion-select-option>
</ion-select>
</div>
</div>
<div class="line">
<div align="center" class="input-class">
<ion-button (click)="goToAboutPage()" expand="block" color="primary"><ion-spinner *ngIf="loading"></ion-spinner> CONFIRMER <ion-icon name="checkmark-done"></ion-icon></ion-button>
</div>
</div>
</div>
</div>
</ion-content>
RESGISTER.PAGE.TS
import { Component, OnInit } from '#angular/core';
import { AlertController, NavController, ToastController } from '#ionic/angular';
import { AuthService } from 'src/app/services/auth.service';
import { NgForm } from '#angular/forms';
import { AlertService } from 'src/app/services/alert.service';
import {IdentityPage} from 'src/app/identity/identity.page';
import { Router } from '#angular/router';
#Component({
selector: 'app-register',
templateUrl: './register.page.html',
styleUrls: ['./register.page.scss'],
})
export class RegisterPage implements OnInit {
loading: boolean;// loading chamando
country: any;
password:any;
private cod_country;
constructor(
private authService: AuthService,
private navCtrl: NavController,
private alertService: AlertService,
public alertController: AlertController,
private toast: ToastController,
private router: Router,
) {
this.getCountry();
}
ngOnInit() {
}
//Get all country list
getCountry(){
this.authService.getCountry().subscribe(country=>{
this.country = country;
})
}
// navigate to about page
goToAboutPage(data) {
this.router.navigate(['/identity'],{
queryParams:data
})
}
}
There are Multiple Ways to pass data from 1 page to other page.
Method 1:
Use Angular Router with params
Page 1:
goToNewPage(){
this.router.navigate(['/identity'],{
queryParams: JSON.Stringify(data)
})
}
Page 2:
import {ActivatedRoute} from '#angular/router';
constructor(private activatedRoute: ActivatedRoute){
this.activatedRoute.queryParams.subscribe(params => {
console.log(params)
});
}
Method 2:
Create a GlobalDataProviderService.
Run Command:
ionic generate service globaldata
inside Globaldata class:
public static userObject:any;
Import this class on your both pages and initialize your variable.
Page 1:
goToNewPage(){
GlobaldataService.userObject = YourData;
this.router.navigate(['/identity'])
}
Page 2:
import this class:
inside Constructor or lifeCycle Hook.
yourVaribale = GlobaldataService.usrObject;
Method 3 for Real time Update:
Check my Other Answer: Real Time Data Update
Page 1 html code
<ion-row>
<ion-col size="12">
<ion-item>
<ion-label position="stacked">E-Mail</ion-label>
<ion-input type="email" [(ngModel)]="email"></ion-input>
</ion-item>
<ion-item>
<ion-label position="stacked">Password</ion-label>
<ion-input type="password" [(ngModel)]="password"></ion-input>
</ion-item>
<ion-item>
<ion-label>Country</ion-label>
<ion-select placeholder="Select Country" [(ngModel)]="country">
<ion-select-option value="India">India</ion-select-option>
<ion-select-option value="Usa">Usa</ion-select-option>
</ion-select>
</ion-item>
</ion-col>
<ion-col size="12" class="ion-text-center">
<ion-button (click)="goToAboutPage()" expand="block" shape="round">
Click me
</ion-button>
</ion-col>
</ion-row>
Page 1 ts code
public country: string;
public email: string;
public password: string;
constructor(public nav: NavController) {}
goToAboutPage() {
let params: any = {
country: this.country,
email: this.email,
password: this.password
}
this.nav.navigateForward('/identity', { state: params }); // params to pass object/array
}
Page 2
constructor(public router: Router){
if (router.getCurrentNavigation().extras.state) {
const params = this.router.getCurrentNavigation().extras.state;
console.log(params.email)
console.log(params.password)
console.log(params.country)
}
}

Ionic-Vue Ionicons 5.x.x doesn't show icon

I used ionic-vue with ionicons 5.0.1 but after call
<ion-icon name="add"></ion-icon>
i was following https://dev.to/aaronksaunders/build-your-first-ionic-vue-app-18kj and https://github.com/ionic-team/ionic/issues/19078 tutorial, but stucked and icon in FAB cannot be show.
This is my syntax, thank you for helping.
<template>
<ion-page>
....
<ion-fab vertical="bottom" horizontal="end" slot="fixed">
<ion-fab-button #click="$router.push({ name: 'new-item' })">
<ion-icon name="add"></ion-icon>
</ion-fab-button>
</ion-fab>
</ion-content>
</ion-page>
</template>
<script>
...
import { addIcons } from 'ionicons';
import * as allIcons from 'ionicons/icons';
const currentIcons = Object.keys(allIcons).map(i => {
const key = i.replace(/[A-Z]/g, letter => `-${letter.toLowerCase()}`)
if(typeof allIcons[i] === 'string') {
return {
[key]: allIcons[i],
}
}
return {
['ios-' + key]: allIcons[i].ios,
['md-' + key]: allIcons[i].md,
};
});
const iconsObject = Object.assign({}, ...currentIcons);
addIcons(iconsObject);
...
</script>
Result FAB does not show icon 'add':
For Ionic Vue 3 using Composition API:
<template>
<ion-icon :icon="rocket" />
</template>
<script>
import { IonIcon } from '#ionic/vue';
import { rocket } from 'ionicons/icons';
export default {
components: { IonIcon },
setup() {
return {
rocket
}
}
}
</script>
For <script setup>
<script setup>
import { IonIcon } from '#ionic/vue';
import { rocket } from 'ionicons/icons';
</script>
<template>
<ion-icon :icon="rocket" />
</template>
I was also following the same guide(https://dev.to/devmount/how-to-use-ionicons-v5-with-vue-js-53g2), and I encountered the same issue.
I decided to downgrade the ionicons version to version 4:
npm i ionicons#4
This solved my issue.
The code that I used from the guide:
<template>
<ion-page>
<ion-header>
<ion-toolbar color="primary">
<ion-title>Home</ion-title>
</ion-toolbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item>
<ion-checkbox slot="start"></ion-checkbox>
<ion-label>
<h1>Create Ideaa</h1>
<ion-note>Run Idea by Brandy</ion-note>
</ion-label>
<ion-badge color="success" slot="end">5 Days</ion-badge>
</ion-item>
</ion-list>
<ion-fab vertical="bottom" horizontal="end" slot="fixed">
<ion-fab-button >
<ion-icon name="add" ></ion-icon>
</ion-fab-button>
</ion-fab>
</ion-content>
</ion-page>
</template>
<script>
import { add } from "ionicons/icons";
import { addIcons } from "ionicons";
addIcons({
"ios-add": add.ios,
"md-add": add.md
});
export default {
name: "HomePage",
props: {
msg: String
}
};
</script>
In your main.js file
import * as allIcons from "ionicons/icons";
Vue.mixin({
data() {
return {
i: allIcons,
};
},
methods: {
icon(name) {
return this.i[name];
}
}
});
now you can use <ion-icon :src="icon('search')"></ion-icon> anywhere in the vue application, it is going to work
hey thanks for checking out the blogs and videos...
you can also get the icons this way...
<template>
<ion-button #click="handleAddItemClicked" >
<ion-icon slot="icon-only" :src="i.saveOutline" ></ion-icon>
</ion-button>
<ion-button #click="handleAddItemClicked" >
<ion-icon slot="icon-only" :src="i.save" ></ion-icon>
</ion-button>
<ion-button #click="handleAddItemClicked" >
<ion-icon slot="icon-only" :src="i.saveSharp" ></ion-icon>
</ion-button>
</template>
<script>
import * as allIcons from "ionicons/icons";
...
data() {
return {
i : allIcons,
};
},
</script>
I followed this comment in a closed issue on #modus/ionic-vue repo: https://github.com/ModusCreateOrg/ionic-vue/issues/120#issuecomment-633666592
import { addIcons } from 'ionicons'
import { add, cartOutline } from 'ionicons/icons'
addIcons({ add, "cart-outline": cartOutline })
This worked with ionicons#5.1.2 installed. Note how the multi word icon imports are camel case instead of kebab case. If you want to use the kebab case variant of the name for an ion-icon you have to do the assignment to the kebab case name yourself like in the case of cart-outline above.
Though if you wanted to add all of them at once and support kebab case, you could map a new object like this:
import { addIcons } from 'ionicons'
import * as allIcons from 'ionicons/icons'
import _ from 'lodash'
addIcons(_.mapKeys(allIcons, (value, key) => _.kebabCase(key))
After i tried everything, there weren't any errors reported anywehere, just icon wasn't there.
Please check twice, that you have set the color of the icon, because in default icon style color is inhereit.
So, if you have for example, a green button, the color of the icon will be also green, if you do not specify.

How to make ionic 3 autoscroll for chat app work?

I have tried every solution but nothing has worked. I am building a chat app where i want it to be scrolled to last message automatically,also when new message comes it scrolls to the bottom.
I have tried scrollTo() on the #content but it doesn't work
chat.html
<ion-content #content *ngIf="buddy">
<div class = "chatwindow">
<ion-list no-lines *ngIf="allmessages">
<ion-item *ngFor = "let item of allmessages; let i = index" text-wrap>
<ion-avatar item-left *ngIf="item.sentby === buddy.uid">
<img src="{{buddy?.photoURL}}">
</ion-avatar>
<div class="bubble me" *ngIf="item.sentby === buddy.uid">
<h3 *ngIf="!imgornot[i]">{{item.message}}</h3>
<img src="{{item?.message}}" *ngIf="imgornot[i]">
</div>
<ion-avatar item-right *ngIf="item.sentby != buddy.uid">
<img src="{{photoURL}}">
</ion-avatar>
<div class="bubble you" *ngIf="item.sentby != buddy.uid">
<h3 *ngIf="!imgornot[i]">{{item.message}}</h3>
<img src="{{item?.message}}" *ngIf="imgornot[i]">
</div>
</ion-item>
</ion-list>
</div>
</ion-content>
chat.ts
#ViewChild('content') content: Content;
scrolltoBottom() {
setTimeout(() => {
// this.content.scrollToBottom();
}, 1000);
}
Your code should be like this.
export class ChatPage {
#ViewChild('content') content: Content;
constructor(public navCtrl: NavController) {
this.scrolltoBottom()
}
scrolltoBottom() {
setTimeout(() => {
this.content.scrollToBottom();
}, 300);
} }

Ionic 2 Maximum call stack size exceeded Error

Trying to figure out this problem. I am getting a maxmimum call stack size error and the link below is the js output.
I have added print statements and worked out the main app file is calling page1 as it should but then page1 is calling the main app file and this continues.
I am new to ionic 2 and would really appreciate a solution, thanks.
Javascript Output
page1.ts
import { Component } from '#angular/core';
import { Data } from '../../providers/data';
import { NewListPage } from '../new-list/new-list';
import { NavController } from 'ionic-angular';
#Component({
selector: 'page-page1',
templateUrl: 'page1.html',
})
export class Page1 {
public list: any[] = [];
constructor(public navCtrl: NavController, private _data: Data) {
console.log('Page1BEFORE');
let that = this;
this._data.list.subscribe((data) => {that.list.push(data);}, (err) => {console.error(err);});
}
newList() {
console.log('NEWLIST1');
this.navCtrl.push(NewListPage);
}
}
page1.html
<ion-app>
<ion-header>
<ion-navbar>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Page One</ion-title>
<ion-buttons end>
<ion-icon ios="ios-contact" md="md-contact"></ion-icon>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content class="grid-basic-page">
<ion-col width-100><progress class="progressBar" max="100" value="80"></progress></ion-col>
<ion-row>
<ion-col width-50><div>col</div></ion-col>
<ion-col width-50><div>col</div></ion-col>
</ion-row>
<ion-row>
<ion-col width-50><div>col</div></ion-col>
<ion-col width-50><div>col</div></ion-col>
</ion-row>
<ion-row>
<ion-col width-50><div>col</div></ion-col>
<ion-col width-50><div>col</div></ion-col>
</ion-row>
<ion-list *ngIf="list">
<ion-item *ngFor="let item of list">
<ion-label>{{item.title}}</ion-label>
</ion-item>
</ion-list>
<p *ngIf="!list"> No Lists </p>
<button fab fab-bottom fab-right (click)="newList()"> New </button>
</ion-content>
</ion-app>
app.component.ts
import { Component, ViewChild } from '#angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { Page1 } from '../pages/page1/page1';
import { Page2 } from '../pages/page2/page2';
import { Data } from '../providers/data';
#Component({
templateUrl: 'app.html',
providers: [Data],
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage: any = Page1;
pages: Array<{title: string, component: any}>;
constructor(public platform: Platform) {
console.log('PreAPP');
this.initializeApp();
console.log('PostApp');
// used for an example of ngFor and navigation
this.pages = [
{ title: 'Page One', component: Page1 },
{ title: 'Page Two', component: Page2 }
];
console.log('pages');
}
initializeApp() {
console.log('APP');
this.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();
});
}
openPage(page) {
console.log('OpenPAGE');
// Reset the content nav to have just this page
// we wouldn't want the back button to show in this scenario
this.nav.setRoot(page.component);
}
}
app.html
<ion-menu [content]="content">
<ion-header>
<ion-toolbar>
<ion-title>Menu</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<button menuClose ion-item *ngFor="let p of pages" (click)="openPage(p)">
{{ p.title }}
</button>
</ion-list>
</ion-content>
</ion-menu>
<!-- Disable swipe-to-go-back because it's poor UX to combine STGB with side menus -->
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>
Removing the <ion-app> element from page1.html fixed the issue
In my case I had not declared and added routes constant in imports array of the module. Once declared and imported error gone.
I am using IONIC 4

Ionic2 JWT authentication failed with Django rest framework backend

I am building an Ionic 2 app and I am trying to use JWT to authenticate my users as shown here: https://auth0.com/blog/2016/02/18/ionic-2-authentication-how-to-secure-your-mobile-app-with-jwt/.
On clicking 'login' server sends back the token which I can see in my developer console network, however I get following error on console: (Error in build/pages/profile/profile.html:8:29 & ORIGINAL EXCEPTION: Error: JWT must have 3 parts.)Additionally I have to clear cookies everytime!
My profile.ts:
import {Page, Storage, LocalStorage} from 'ionic-angular';
import {Http, Headers} from '#angular/http';
import {FORM_DIRECTIVES} from '#angular/common';
import {JwtHelper} from 'angular2-jwt';
import {AuthService} from '../../services/auth/auth.service';
import 'rxjs/add/operator/map';
import { NavController, NavParams } from 'ionic-angular';
import { StartPage } from '../start/start.component';
#Page({
templateUrl: 'build/pages/profile/profile.html',
directives: [FORM_DIRECTIVES]
})
export class ProfilePage {
LOGIN_URL: string = " http://127.0.0.1:8000/rest-auth/login/";
SIGNUP_URL: string = "http://127.0.0.1:8000/rest-auth/registration/";
auth: AuthService;
// When the page loads, we want the Login segment to be selected
authType: string = "login";
// We need to set the content type for the server
contentHeader: Headers = new Headers({"Content-Type": "application/json"});
error: string;
jwtHelper: JwtHelper = new JwtHelper();
local: Storage = new Storage(LocalStorage);
user: string;
constructor(private http: Http, public nav:NavController) {
this.auth = AuthService;
this.local.get('profile').then(profile => {
this.user = JSON.parse(profile);
}).catch(error => {
console.log(error);
});
}
login(credentials) {
this.http.post(this.LOGIN_URL, JSON.stringify(credentials), { headers: this.contentHeader })
.map(res => res.json())
.subscribe(
data => this.authSuccess(data.id_token),
err => this.error = err
);
}
signup(credentials) {
this.http.post(this.SIGNUP_URL, JSON.stringify(credentials), { headers: this.contentHeader })
.map(res => res.json())
.subscribe(
data => this.authSuccess(data.id_token),
err => this.error = err
);
}
logout() {
this.local.remove('id_token');
this.user = null;
}
authSuccess(token) {
this.error = null;
this.local.set('id_token', token);
this.user = this.jwtHelper.decodeToken(token);
}
}
My service:
import {tokenNotExpired} from 'angular2-jwt';
export class AuthService {
constructor() {}
public static authenticated() {
return tokenNotExpired();
}
}
My profile.html:
<!-- app/profile/profile.html -->
<ion-navbar *navbar>
<button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Profile</ion-title>
</ion-navbar>
<ion-content class="login" *ngIf="!auth.authenticated()">
<div padding>
<ion-segment [(ngModel)]="authType">
<ion-segment-button value="login">
Login
</ion-segment-button>
<ion-segment-button value="signup">
Signup
</ion-segment-button>
</ion-segment>
</div>
<div [ngSwitch]="authType">
<form *ngSwitchWhen="'login'" #loginCreds="ngForm" (ngSubmit)="login(loginCreds.value)">
<ion-item>
<ion-label>Username</ion-label>
<ion-input type="text" ngControl="email"></ion-input>
</ion-item>
<ion-item>
<ion-label>Password</ion-label>
<ion-input type="password" ngControl="password"></ion-input>
</ion-item>
<div padding>
<button block type="submit">Login</button>
</div>
</form>
<form *ngSwitchWhen="'signup'" #signupCreds="ngForm" (ngSubmit)="signup(signupCreds.value)">
<ion-item>
<ion-label>Username</ion-label>
<ion-input type="text" ngControl="username"></ion-input>
</ion-item>
<ion-item>
<ion-label>Password</ion-label>
<ion-input type="password" ngControl="password"></ion-input>
</ion-item>
<div padding>
<button block type="submit">Signup</button>
</div>
</form>
</div>
<div padding>
<p *ngIf="error" class="error">{{ error._body }}</p>
</div>
</ion-content>
<ion-content>
<div *ngIf="auth.authenticated()">
<div padding>
<h1>Welcome, {{ user }}</h1>
<button block (click)="logout()">Logout</button>
</div>
</div>
</ion-content>
On successful login I would like to navigate to a specific page. What's going wrong and how can I fix this?
Also, the token I get back from my backend (I am using Django-rest-auth in my backend for authentication):