How can I change an item in app.component.ts? - ionic-framework

I am working on a project in Ionic, and when I login, I did set the storage('id') which was used in the app.component.ts to get the user details, but when I run the code, it didn't work, but when I reload the whole page (Ctrl + R), it then works.
Here is my code.
login.ts:
import {Component} from "#angular/core";
import {NavController, AlertController, ToastController, MenuController} from "ionic-angular";
import {HomePage} from "../home/home";
import {RegisterPage} from "../register/register";
import { ServicesProvider } from '../../providers/services/services';
import { Storage } from '#ionic/storage';
#Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {
private user = {
email: '',
password: ''
}
private setputt:string;
constructor(public navCtrl: NavController,
public forgotCtrl: AlertController,
public menu: MenuController,
public toastCtrl: ToastController,
private storage: Storage,
public ServicesProvider: ServicesProvider
) {
this.menu.swipeEnable(false);
}
register() {
this.navCtrl.setRoot(RegisterPage);
}
login(user){
this.ServicesProvider.loginpost(user).subscribe(
data => {
if(data.success){
this.setputt = data.message;
if(this.setputt == 'Login Successfull'){
this.storage.set('id', data.id);
this.navCtrl.setRoot(HomePage);
}
}
else{
this.setputt = data.message;
}
},
error => {
console.log(error);
}
)
}
// set a key/value
// storage.set('name', 'Max');
// // Or to get a key/value pair
// storage.get('age').then((val) => {
// console.log('Your age is', val);
// });
// storage.remove('name');
forgotPass() {
let forgot = this.forgotCtrl.create({
title: 'Forgot Password?',
message: "Enter you email address to send a reset link password.",
inputs: [
{
name: 'email',
placeholder: 'Email',
type: 'email'
},
],
buttons: [
{
text: 'Cancel',
handler: data => {
console.log('Cancel clicked');
}
},
{
text: 'Send',
handler: data => {
console.log('Send clicked');
let toast = this.toastCtrl.create({
message: 'Email was sended successfully',
duration: 3000,
position: 'top',
cssClass: 'dark-trans',
closeButtonText: 'OK',
showCloseButton: true
});
toast.present();
}
}
]
});
forgot.present();
}
}
app.component.ts:
import { Component, ViewChild } from '#angular/core';
import { Platform, Nav } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { Storage } from '#ionic/storage';
import { ServicesProvider } from '../providers/services/services';
import { HomePage } from '../pages/home/home';
import {LoginPage} from "../pages/login/login";
import {ProfilePage} from "../pages/profile/profile";
import {FriendsPage} from "../pages/friends/friends";
import {YearbooksPage} from "../pages/yearbooks/yearbooks";
import {ChatPage} from "../pages/chat/chat";
import {FilesPage} from "../pages/files/files";
import {CheckLoginPage} from "../pages/check-login/check-login";
export interface MenuItem {
title: string;
component: any;
icon: string;
}
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage: any = CheckLoginPage;
appMenuItems: Array<MenuItem>;
public FullNamer;
public pixr;
public id:number;
constructor(
platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen,
public storage: Storage,
public ServicesProvider: ServicesProvider
) {
platform.ready().then(() => {
statusBar.styleDefault();
splashScreen.hide();
});
this.storage.get('id').then((vals) => {
if (vals != null) {
this.ServicesProvider.getDetails(vals).subscribe(data=>{
// console.log(data);
this.pixr = this.ServicesProvider.theurl+data.pix;
this.FullNamer = data.fullname;
});
}
});
this.appMenuItems = [
{title: 'Home', component: HomePage, icon: 'home'},
{title: 'Files', component: FilesPage, icon: 'ios-folder'},
{title: 'Friends', component: FriendsPage, icon: 'ios-people'},
{title: 'Yearbooks', component: YearbooksPage, icon: 'ios-book'},
{title: 'Chat', component: ChatPage, icon: 'md-chatbubbles'}
];
}
ionViewCanEnter(){
}
openPage(page) {
this.nav.setRoot(page.component);
}
GoPages(){
this.nav.setRoot(ProfilePage);
}
logout() {
this.storage.remove('id');
this.storage.remove('FullName');
this.nav.setRoot(LoginPage);
}
}
app.html
<ion-menu side="left" id="authenticated" [content]="content">
<ion-header>
<ion-toolbar class="user-profile">
<ion-grid>
<ion-row>
<ion-col col-4>
<div class="user-avatar">
<img [src]="pixr">
</div>
</ion-col>
<ion-col padding-top col-8>
<h2 ion-text class="no-margin bold text-white">
{{FullNamer}}
</h2>
<span ion-text color="light">Customer</span>
</ion-col>
</ion-row>
<ion-row no-padding class="other-data">
<ion-col no-padding class="column">
<button ion-button icon-left small full class="round" color="light" menuClose (click)="GoPages()">
<ion-icon name="ios-person"></ion-icon>
Edit Profile
</button>
</ion-col>
<ion-col no-padding class="column">
<button ion-button icon-left class="round" small full color="light" menuClose (click)="logout()">
<ion-icon name="log-out"></ion-icon>
Log Out
</button>
</ion-col>
</ion-row>
</ion-grid>
</ion-toolbar>
</ion-header>
<ion-content color="primary">
<ion-list class="user-list">
<button ion-item menuClose class="text-1x" *ngFor="let menuItem of appMenuItems" (click)="openPage(menuItem)">
<ion-icon item-left [name]="menuItem.icon" color="primary"></ion-icon>
<span ion-text color="primary">{{menuItem.title}}</span>
</button>
</ion-list>
</ion-content>
</ion-menu>
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>
service.ts:
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Storage } from '#ionic/storage';
#Injectable()
export class ServicesProvider {
public theurl = 'http://localhost/HoleeSheet/php/';
public tittle = 'Holee Sheet';
public id:number;
constructor(public http: HttpClient, private storage: Storage) {
this.storage.get('id').then((valr) => {
if (valr != null) {
this.id = valr;
}
});
}
loginpost(user){
return this.http.put<obbbbs>(this.theurl+'login.php', {
email: user.email,
password: user.password
});
}
getDetails(humid){
console.log(humid);
return this.http.post<details>(this.theurl+'getDetails.php', {
id: humid
});
}
}
interface details{
'fullname': string,
'pix':string
}
interface obbbbs {
'success': 'boolean',
'message': 'string',
'id': 'string'
}
How can I solve this issue?

Welcome to Stack Overflow.
// LoginPage.login method (login.ts)
this.storage.set('id', data.id);
this.navCtrl.setRoot(HomePage);
You're navigating to the home page before the value gets saved to storage. You should wait until the promise returned by this.storage.set is resolved before continuing navigation:
// LoginPage.login method (login.ts)
this.storage.set('id', data.id)
.then(() => this.navCtrl.setRoot(HomePage));

Related

How to Manage Session in side menu in Ionic 4?

Ionic app with a side menu
Here my app concept is Blog App
in this I need to log-in, profile, etc
Ionic app with a side menu
if user want to like or comment any blog post he must log-in first
so I want to manage session if the already log-in user so hide log-in ion-item from side menu else logout ion-item vise-Versa
Here is code
home.html
<ion-app>
<ion-split-pane contentId="main-content" >
<ion-menu contentId="main-content" >
<ion-header>
<ion-toolbar color="primary">
<ion-title>Lady Help Lady</ion-title>
</ion-toolbar>
</ion-header>
<ion-content color="primary">
<ion-list >
<ion-menu-toggle auto-hide="false" *ngFor="let p of appPages">
<ion-item color="primary" [routerDirection]="'root'" [routerLink]="[p.url]">
<ion-icon slot="start" [name]="p.icon" color="light"></ion-icon>
<ion-label color="light">
{{p.title}}
</ion-label>
</ion-item>
</ion-menu-toggle>
<ion-menu-toggle auto-hide="false" >
<ion-item color="primary" *ngIf="showBtnLogin">
<ion-icon slot="start" name="log-in" color="light"></ion-icon>
<ion-label color="light" (click)="login()">
Login
</ion-label>
</ion-item>
<ion-item color="primary" *ngIf="!showBtnLogin">
<ion-icon slot="start" name="log-out" color="light"></ion-icon>
<ion-label color="light" (click)="logout()" > Log Out</ion-label>
</ion-item>
</ion-menu-toggle>
</ion-list>
</ion-content>
</ion-menu>
<ion-router-outlet id="main-content"></ion-router-outlet>
</ion-split-pane>
</ion-app>
home.page.ts
import { Component, OnInit } from '#angular/core';
import { Router} from '#angular/router';
import { MenuController } from '#ionic/angular';
import { AuthService } from '../services/auth.service';
import { StorageService } from '../services/storage.service';
#Component({
selector: 'app-home',
templateUrl: './home.page.html',
styleUrls: ['./home.page.scss'],
})
export class HomePage implements OnInit {
public appPages = [
{
title: 'Blog',
url: '/home/blog',
icon: 'home'
},
{
title: 'Profile',
url: '/home/profile',
icon: 'cog'
},
{
title: 'Change Password',
url: '/home/change-password',
icon: 'lock'
},
{
title: 'About Us',
url: '/home/about-us',
icon: 'cog'
},
{
title: 'Privacy Policy',
url: '/home/privacy-policy',
icon: 'settings'
}
,
{
title: 'Terms & Conditions',
url: '/home/terms-conditions',
icon: 'paper'
},
{
title: 'Enable Location',
url: '/home/enable-location',
icon: 'pin'
}
,
{
title: 'Donation',
url: '/home/donation',
icon: 'card'
}
];
public authUser: any;
showBtnLogin = true;
// showBtnLogout: boolean = true;
currentUser: any;
constructor(private router: Router,
private authService: AuthService,
private menu: MenuController,
public storageService: StorageService) { }
ngOnInit() {
this.authService.userData$.subscribe((res: any) => {
this.authUser = res;
if (res === null) {
console.log(res);
this.showBtnLogin = false;
} else {
this.showBtnLogin = true;
}
});
}
logout() {
this.authService.logout();
}
login() {
this.router.navigate(['/home/login']);
}
}
login.page.ts
validateInputs() {
const mobile = this.postData.mobile.trim();
const password = this.postData.password.trim();
return (
this.postData.mobile &&
this.postData.password &&
mobile.length > 0 &&
password.length > 0
);
}
formLogin() {
if (this.validateInputs()) {
this.loader.loadingPresent();
console.log(this.postData);
this.authService.login(this.postData).subscribe(
(res: any) => {
if (res.status === true) {
this.loader.loadingDismiss();
// Storing the User data.
this.storageService.store(AuthConstants.AUTH, res.logindata);
this.router.navigate(['/home/blog']);
} else {
this.loader.loadingDismiss();
this.toastService.presentToast(res.error);
}
},
(error: any) => {
this.loader.loadingDismiss();
this.toastService.presentToast('Network Issue.');
}
);
} else {
this.loader.loadingDismiss();
this.toastService.presentToast('Please enter mobile or password.');
}
}
StorageService.ts
import { Injectable } from '#angular/core';
import { Plugins } from '#capacitor/core';
const { Storage } = Plugins;
#Injectable({
providedIn: 'root'
})
export class StorageService {
constructor() { }
// Store the value
async store(storageKey: string, value: any) {
const encryptedValue = btoa(escape(JSON.stringify(value)));
await Storage.set({
key: storageKey,
value: encryptedValue
});
}
// Get the value
async get(storageKey: string) {
const ret = await Storage.get({ key: storageKey });
return JSON.parse(unescape(atob(ret.value)));
}
async removeStorageItem(storageKey: string) {
await Storage.remove({ key: storageKey });
}
// Clear storage
async clear() {
await Storage.clear();
}
}
You can also do that like this
in your html
<ion-menu-toggle auto-hide="false" >
<ion-item color="primary" *ngIf="showBtnLogin">
<ion-icon slot="start" name="log-in" color="light"></ion-icon>
<ion-label color="light" (click)="login()">
Login
</ion-label>
</ion-item>
<ion-item color="primary" *ngIf="!showBtnLogin">
<ion-icon slot="start" name="log-out" color="light"></ion-icon>
<ion-label color="light" (click)="logout()" > Log Out</ion-label>
</ion-item>
</ion-menu-toggle>
in your .ts
showBtnLogin: boolean = true;
currentUser: any;
ngOnInit() {
this.authService.userData$.subscribe((res: any) => {
this.authUser = res;
// this.postData.user_id = res.id;
console.log(this.authUser.id);
this.currentUser = this.authUser;
if (res === null) {
this.showBtnLogin = true;
} else {
this.showBtnLogin = false;
}
});
}
logout() {
this.authService.logout();
}
login() {
this.router.navigate(['/home/login']);
}
Change some code in your .ts file here it is
showBtnLogin = true;
public appPages = [
{
title: 'Blog',
url: '/home/blog',
icon: 'home'
},
{
title: 'Profile',
url: '/home/profile',
icon: 'cog',
status: true
},
{
title: 'Change Password',
url: '/home/change-password',
icon: 'lock',
status: true
},
{
title: 'About Us',
url: '/home/about-us',
icon: 'cog',
status: true
},
{
title: 'Privacy Policy',
url: '/home/privacy-policy',
icon: 'settings',
status: true
}
,
{
title: 'Terms & Conditions',
url: '/home/terms-conditions',
icon: 'paper',
status: true
},
{
title: 'Enable Location',
url: '/home/enable-location',
icon: 'pin',
status: true
}
,
{
title: 'Donation',
url: '/home/donation',
icon: 'card',
status: true
}
];
In your ngOnInit
ngOnInit() {
this.authService.userData$.subscribe((res: any) => {
this.authUser = res;
if (res === null) {
console.log(res);
this.showBtnLogin = false;
for (let i = 0; i < this.appPages.length; i++) {
if (this.appPages[i].title == 'Profile') {
this.appPages[i].status = false;
}
if (this.appPages[i].title == 'Change Password') {
this.appPages[i].status = false;
}
}
} else {
this.showBtnLogin = true;
}
});
}
if your profile and change password index not change then you can directly change status via index without using for loop
and finally in your logout
logout() {
this.authService.logout();
for (let i = 0; i < this.appPages.length; i++) {
if (this.appPages[i].title == 'Profile') {
this.appPages[i].status = false;
}
if (this.appPages[i].title == 'Change Password') {
this.appPages[i].status = false;
}
}
}
In your .html file
<ion-list>
<ion-menu-toggle auto-hide="false" *ngFor="let p of appPages">
<ion-item [routerDirection]="'root'" [routerLink]="[p.url]" *ngIf="p.status">
<ion-icon slot="start" [name]="p.icon"></ion-icon>
<ion-label>
{{p.title}}
</ion-label>
</ion-item>
</ion-menu-toggle>
<ion-menu-toggle auto-hide="false">
<ion-item color="primary" *ngIf="showBtnLogin">
<ion-icon slot="start" name="log-in" color="light"></ion-icon>
<ion-label color="light" (click)="login()">
Login
</ion-label>
</ion-item>
<ion-item color="primary" *ngIf="!showBtnLogin">
<ion-icon slot="start" name="log-out" color="light"></ion-icon>
<ion-label color="light" (click)="logout()"> Log Out</ion-label>
</ion-item>
</ion-menu-toggle>
</ion-list>

Ionic 3 Tab Navigation + side menu

The issue I am having is that when I use these both together, Tab navigation dissapears when using side menu navigation.
Using tab navigation makes the app work similar to a SPA i'm assuming, in that the page is loaded in the view. However, when I navigate using the side menu, I go directly to that page, which is circumventing the point of the tab navigation.
Is there a way to make these both work together?
app.component.ts:
import { Component, ViewChild } from '#angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { HomePage } from '../pages/home/home';
import { Settings } from '../pages/settings/settings';
import { Journeys } from '../pages/journeys/journeys';
import { TabsPage } from '../pages/tabs/tabs';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage: any = TabsPage;
pages: Array<{title: string, component: any}>;
constructor(public platform: Platform, public statusBar: StatusBar,
public splashScreen: SplashScreen) {
this.initializeApp();
this.pages = [
{ title: 'Home', component: HomePage },
{ title: 'Settings', component: Settings },
{ title: 'Journeys', component: Journeys }
];
}
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
openPage(page) {
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>
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>
Tabs.ts:
import { Component } from '#angular/core';
import { HomePage } from '../home/home';
import { Journeys } from '../journeys/journeys';
import { Settings } from '../settings/settings';
#Component({
templateUrl: 'tabs.html'
})
export class TabsPage {
tab1Root = HomePage;
tab2Root = Journeys;
tab3Root = Settings;
constructor() {
}
}
Tabs.html:
<ion-tabs>
<ion-tab [root]="tab1Root" tabTitle='Home' tabIcon='ios-home'></ion-tab>
<ion-tab [root]="tab2Root" tabTitle='Journeys' tabIcon='ios-car'></ion-tab>
<ion-tab [root]="tab3Root" tabTitle='Settings' tabIcon='md-settings'></ion-tab>
homepage.html:
<ion-header>
<ion-navbar>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Home</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-grid>
<ion-row>
<ion-col col-12>
<p class='homepage_placeholder'>Homepage Placeholder</p>
</ion-col>
</ion-row>
</ion-grid>
</ion-content>
Firstly, add tabIndex to your this.pages
this.pages = [
{ title: 'Home', component: HomePage, tabIndex:0 },
{ title: 'Settings', component: Settings, tabIndex:1 },
{ title: 'Journeys', component: Journeys, tabIndex:2 }
{ title: 'PageNotInTab', component: componentName }
];
And then, make your openPage() like this
openPage(page): void{
if(page.tabIndex){
this.nav.setRoot(TabsPage,{selectedIndex:page.tabIndex})
}else{
this.nav.setRoot(page.component,{})
}
}
Of cousre, TabsPage should be prepared before implementing the code above.
I leave out the details.
In TabsPage
ngAfterContentInit(){
if(this.navParams.data.hasOwnProperty("selectedIndex"))
this._selectedIndex = this.navParams.get("selectedIndex")
else
this._selectedIndex=0;
}

ionic2 left side menu background color changing after clicked

How to change left menu item's background color after clicked on left side menu in ionic 2 .
I have attached 2 images. when I clicked notifications menu I want to change its background color like image 2.
You can use ngClass
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)" [ngClass]="{'selectedMenu' : (p.title == selectedmenu)}">
{{p.title}}
</button>
</ion-list>
</ion-content>
</ion-menu>
<ion-nav [root]="rootPage" #content swipeBackEnabled="false"></ion-nav>
app.component.ts
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { HomePage } from '../pages/home/home';
#Component({
templateUrl: 'app.html'
})
export class MyApp
{
rootPage:any = HomePage;
pages: Array<{title: string, component: any}>;
selectedmenu: String;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen)
{
this.pages = [
{ title: 'Home', component: HomePage },
{ title: 'Contact', component: HomePage },
{ title: 'About', component: HomePage },
{ title: 'Notification', component: HomePage },
];
platform.ready().then(() =>
{
statusBar.styleDefault();
splashScreen.hide();
});
}
openPage(obj)
{
this.selectedmenu = obj.title;
}
}

ionic3 - Can't resolve all parameters for UserDataProvider: ([object Object], [object Object], ?)

This is Ionic3 project and I was doing login page.
This page I want to show login button first in slide menu, after I login into apps, hidden login button and showing logout button. But when I was doing it this error coming out:
Can't resolve all parameters for UserDataProvider: ([object Object],
[object Object], ?).
This is my ionic info:
Ionic Framework: 3.6.0
Ionic Native: 2.4.1
Ionic App Scripts: 2.1.3
Angular Core: 4.0.0
Angular Compiler CLI: 4.0.0
Node: 6.11.3
OS Platform: macOS Sierra
Navigator Platform: MacIntel
User Agent: Mozilla/5.0 (Macintosh; Intel
app.component.ts
import { Component, ViewChild } from '#angular/core';
import { Events, MenuController, Nav, Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { QQSDK, QQShareOptions } from '#ionic-native/qqsdk';
import { Facebook, FacebookLoginResponse } from '#ionic-native/facebook';
import { TabsPage } from '../pages/tabs/tabs';
declare var Wechat:any;
export interface PageInterface {
title: string;
name: string;
component: any;
icon: string;
logsOut?: boolean;
index?: number;
tabName?: string;
tabComponent?: any;
}
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
appPages: PageInterface[] = [
{ title: 'News', name: 'TabsPage', component: TabsPage, index: 0, icon: 'ios-globe-outline' }
];
loggedInPages: PageInterface[] = [
{ title: 'News', name: 'TabsPage', component: TabsPage, index: 0, icon: 'ios-globe-outline' },
{ title: 'Logout', name: 'TabsPage', component: TabsPage, icon: 'log-out', logsOut: true }
];
userData = null;
rootPage = TabsPage;
pages: Array<{title: string, component: any}>;
constructor(public platform: Platform, public events: Events, public menu: MenuController,
private qq: QQSDK,private fb: Facebook) {
this.initializeApp();
this.userData.hasLoggedIn().then((hasLoggedIn) => {
this.enableMenu(hasLoggedIn === true);
});
this.enableMenu(true);
this.listenToLoginEvents();
}
openPage(page: PageInterface) {
let params = {};
if (page.index) {
params = { tabIndex: page.index };
}
if (this.nav.getActiveChildNavs().length && page.index != undefined) {
this.nav.getActiveChildNavs()[0].select(page.index);
} else {
// Set the root of the nav with params if it's a tab index
this.nav.setRoot(page.name, params).catch((err: any) => {
console.log(`Didn't set nav root: ${err}`);
});
}
if (page.logsOut === true) {
// Give the menu time to close before changing to logged out
this.userData.logout();
}
}
listenToLoginEvents() {
this.events.subscribe('user:login', () => {
this.enableMenu(true);
});
this.events.subscribe('user:signup', () => {
this.enableMenu(true);
});
this.events.subscribe('user:logout', () => {
this.enableMenu(false);
});
}
enableMenu(loggedIn: boolean) {
this.menu.enable(loggedIn, 'loggedInMenu');
this.menu.enable(!loggedIn, 'loggedOutMenu');
}
isActive(page: PageInterface) {
let childNav = this.nav.getActiveChildNavs()[0];
// Tabs are a special case because they have their own navigation
if (childNav) {
if (childNav.getSelected() && childNav.getSelected().root === page.tabComponent) {
return 'primary';
}
return;
}
if (this.nav.getActive() && this.nav.getActive().name === page.name) {
return 'primary';
}
return;
}
initializeApp() {
this.platform.ready().then(() => {
StatusBar.styleDefault();
Splashscreen.hide();
});
}
QQLogin(){
const loginOptions: QQShareOptions = {
client: this.qq.ClientType.QQ,
};
this.qq.ssoLogin(loginOptions)
.then((result) => {
console.log('shareNews success');
alert('token is ' + result.access_token);
alert('userid is ' + result.userid);
})
.catch(error => {
console.log(error);
});
this.qq.logout().then(() => {
console.log('logout success');
}).catch(error => {
console.log(error);
});
}
wechatLogin(){
let scope = "snsapi_userinfo",
state = "_" + (+new Date());
Wechat.auth(scope, state, function (response) {
// you may use response.code to get the access token.
alert(JSON.stringify(response));
}, function (reason) {
alert("Failed: " + reason);
});
}
weiboLogin(){}
FBLogin(){
this.fb.login(['email', 'public_profile']).then((response: FacebookLoginResponse) => {
this.fb.api('me?fields=id,name,email,first_name,picture.width(360).height(360).as(picture_large)', []).then(profile => {
this.userData = {email: profile['email'], first_name: profile['first_name'], picture: profile['picture_large']['data']['url'], username: profile['name']}
});
});
}
}
EDIT:
app.html
<ion-menu id="loggedOutMenu" [content]="content">
<ion-header>
<ion-toolbar color="danger">
<ion-title>菜单</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<ion-list-header>请登录</ion-list-header>
<button style="width:40%" ion-button round outline (click)= "QQLogin()">
<ion-icon name="minan-qq"></ion-icon>
</button>
<button color="wechat" style="width:40%" ion-button round outline (click)= "wechatLogin()">
<ion-icon name="minan-wechat"></ion-icon>
</button>
<button color="danger" style="width:40%" ion-button round outline (click)= "weiboLogin()">
<ion-icon name="minan-weibo"></ion-icon>
</button>
<button color="facebook" style="width:40%" ion-button round outline (click)= "FBLogin()">
<ion-icon name="minan-facebook"></ion-icon>
</button>
</ion-list>
<ion-list>
<ion-list-header>导航栏1</ion-list-header>
<button menuClose ion-item *ngFor="let p of appPages" (click)="openPage(p)">
<ion-icon item-start [name]="p.icon" [color]="isActive(p)"></ion-icon>
{{p.title}}
</button>
</ion-list>
</ion-content>
</ion-menu>
<ion-menu id="loggedInMenu" [content]="content">
<ion-header>
<ion-toolbar color="danger">
<ion-title>菜单</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-card *ngIf="userData">
<ion-card-header>账号</ion-card-header>
<ion-thumbnail>
<img [src]="userData.picture" />
</ion-thumbnail>
<ion-card-title>{{ userData.username }}</ion-card-title>
<!-- <ion-card-content>
<p>Email: {{ userData.email }}</p>
<p>First Name: {{ userData.first_name }}</p>
</ion-card-content> -->
</ion-card>
<ion-list>
<ion-list-header>导航栏2</ion-list-header>
<button menuClose ion-item *ngFor="let p of loggedInPages" (click)="openPage(p)">
<ion-icon item-start [name]="p.icon" [color]="isActive(p)"></ion-icon>
{{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>
UPDATE:
app.module.ts
import { NgModule, ErrorHandler } from '#angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { QQSDK } from '#ionic-native/qqsdk';
import { Facebook } from '#ionic-native/facebook';
import { SocialSharing } from '#ionic-native/social-sharing';
import { PhotoViewer } from '#ionic-native/photo-viewer';
import { BrowserModule } from '#angular/platform-browser';
import { HttpModule } from '#angular/http';
import { OneSignal } from '#ionic-native/onesignal';
import { IonicStorageModule } from '#ionic/storage';
import { MyApp } from './app.component';
import { SosPage } from '../pages/sos/sos';
import { ServicesPage } from '../pages/services/services';
import { NewsPage } from '../pages/news/news';
import { NewsDetailPage } from '../pages/news-detail/news-detail';
import { ServicesDetailPage } from '../pages/services-detail/services-detail';
import { TabsPage } from '../pages/tabs/tabs';
import { InsurencePage } from '../pages/insurence/insurence';
import { InsurenceDetailPage } from '../pages/insurence-detail/insurence-detail';
import { EducationPage } from '../pages/education/education';
import { EducationDetailPage } from '../pages/education-detail/education-detail';
import { TravelPage } from '../pages/travel/travel';
import { TravelDetailPage } from '../pages/travel-detail/travel-detail';
import { InvestmentPage } from '../pages/investment/investment';
import { InvestmentDetailPage } from '../pages/investment-detail/investment-detail';
import { LifePage } from '../pages/life/life';
import { LifeDetailPage } from '../pages/life-detail/life-detail';
import { NewsDataProvider } from '../providers/news-data/news-data';
import { ServicesDataProvider } from '../providers/services-data/services-data';
import { UserDataProvider } from '../providers/user-data/user-data';
#NgModule({
declarations: [
MyApp,
SosPage,
ServicesPage,
NewsPage,
TabsPage,
NewsPage,
NewsDetailPage,
ServicesDetailPage,
InsurencePage,EducationPage,TravelPage,InvestmentPage,LifePage,
InsurenceDetailPage,TravelDetailPage,InvestmentDetailPage,EducationDetailPage,LifeDetailPage
],
imports: [
BrowserModule,
HttpModule,
IonicStorageModule.forRoot(),
IonicModule.forRoot(MyApp,{
})
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
SosPage,
ServicesPage,
NewsPage,
TabsPage,
NewsPage,
NewsDetailPage,
ServicesDetailPage,
InsurencePage,EducationPage,TravelPage,InvestmentPage,LifePage,
InsurenceDetailPage,TravelDetailPage,InvestmentDetailPage,EducationDetailPage,LifeDetailPage
],
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler},
NewsDataProvider,
ServicesDataProvider,
SocialSharing,
PhotoViewer,
QQSDK,Facebook,
OneSignal,
UserDataProvider]
})
export class AppModule {}
user-data.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import { Events } from 'ionic-angular';
import 'rxjs/add/operator/map';
#Injectable()
export class UserDataProvider {
HAS_LOGGED_IN = 'hasLoggedIn';
constructor(public http: Http, public events: Events, public storage: Storage) {
console.log('Hello UserDataProvider Provider');
}
login(username: string): void {
this.storage.set(this.HAS_LOGGED_IN, true);
this.setUsername(username);
this.events.publish('user:login');
};
signup(username: string): void {
this.storage.set(this.HAS_LOGGED_IN, true);
this.setUsername(username);
this.events.publish('user:signup');
};
logout(): void {
this.storage.remove(this.HAS_LOGGED_IN);
this.storage.remove('username');
this.events.publish('user:logout');
};
setUsername(username: string): void {
this.storage.set('username', username);
};
getUsername(): Promise<string> {
return this.storage.get('username').then((value) => {
return value;
});
};
hasLoggedIn(): Promise<boolean> {
return this.storage.get(this.HAS_LOGGED_IN).then((value) => {
return value === true;
});
};
}
please update your code file as below
user-data.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import { Events } from 'ionic-angular';
import { Storage } from '#ionic/storage';
import 'rxjs/add/operator/map';
#Injectable()
export class UserDataProvider {
HAS_LOGGED_IN = 'hasLoggedIn';
constructor(public http: Http, public events: Events, public storage: Storage) {
console.log('Hello UserDataProvider Provider');
}
login(user: any): void {
this.storage.set(this.HAS_LOGGED_IN, true);
this.setUser(user);
this.events.publish('user:login');
};
signup(user: any): void {
this.storage.set(this.HAS_LOGGED_IN, true);
this.setUser(user);
this.events.publish('user:signup');
};
logout(): void {
this.storage.remove(this.HAS_LOGGED_IN);
this.storage.remove('username');
this.events.publish('user:logout');
};
setUser(user: any): void {
this.storage.set('user', user);
};
getUser(): Promise<any> {
return this.storage.get('user').then((value) => {
return value;
});
};
hasLoggedIn(): Promise<boolean> {
return this.storage.get(this.HAS_LOGGED_IN).then((value) => {
return value === true;
});
};
}
app.component.ts
import { Component, ViewChild } from '#angular/core';
import { Events, MenuController, Nav, Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { QQSDK, QQShareOptions } from '#ionic-native/qqsdk';
import { Facebook, FacebookLoginResponse } from '#ionic-native/facebook';
import { UserDataProvider } from '../src/to/user-data'
import { TabsPage } from '../pages/tabs/tabs';
declare var Wechat:any;
export interface PageInterface {
title: string;
name: string;
component: any;
icon: string;
logsOut?: boolean;
index?: number;
tabName?: string;
tabComponent?: any;
}
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
appPages: PageInterface[] = [
{ title: 'News', name: 'TabsPage', component: TabsPage, index: 0, icon: 'ios-globe-outline' }
];
loggedInPages: PageInterface[] = [
{ title: 'News', name: 'TabsPage', component: TabsPage, index: 0, icon: 'ios-globe-outline' },
{ title: 'Logout', name: 'TabsPage', component: TabsPage, icon: 'log-out', logsOut: true }
];
//userData = null;
rootPage = TabsPage;
pages: Array<{title: string, component: any}>;
constructor(public platform: Platform, public events: Events, public menu: MenuController,
private qq: QQSDK,private fb: Facebook, private userData: UserDataProvider) {
this.initializeApp();
this.userData.hasLoggedIn().then((hasLoggedIn) => {
this.enableMenu(hasLoggedIn === true);
});
this.enableMenu(true);
this.listenToLoginEvents();
}
openPage(page: PageInterface) {
let params = {};
if (page.index) {
params = { tabIndex: page.index };
}
if (this.nav.getActiveChildNavs().length && page.index != undefined) {
this.nav.getActiveChildNavs()[0].select(page.index);
} else {
// Set the root of the nav with params if it's a tab index
this.nav.setRoot(page.name, params).catch((err: any) => {
console.log(`Didn't set nav root: ${err}`);
});
}
if (page.logsOut === true) {
// Give the menu time to close before changing to logged out
this.userData.logout();
}
}
listenToLoginEvents() {
this.events.subscribe('user:login', () => {
this.enableMenu(true);
});
this.events.subscribe('user:signup', () => {
this.enableMenu(true);
});
this.events.subscribe('user:logout', () => {
this.enableMenu(false);
});
}
enableMenu(loggedIn: boolean) {
this.menu.enable(loggedIn, 'loggedInMenu');
this.menu.enable(!loggedIn, 'loggedOutMenu');
}
isActive(page: PageInterface) {
let childNav = this.nav.getActiveChildNavs()[0];
// Tabs are a special case because they have their own navigation
if (childNav) {
if (childNav.getSelected() && childNav.getSelected().root === page.tabComponent) {
return 'primary';
}
return;
}
if (this.nav.getActive() && this.nav.getActive().name === page.name) {
return 'primary';
}
return;
}
initializeApp() {
this.platform.ready().then(() => {
StatusBar.styleDefault();
Splashscreen.hide();
});
}
QQLogin(){
const loginOptions: QQShareOptions = {
client: this.qq.ClientType.QQ,
};
this.qq.ssoLogin(loginOptions)
.then((result) => {
console.log('shareNews success');
alert('token is ' + result.access_token);
alert('userid is ' + result.userid);
})
.catch(error => {
console.log(error);
});
this.qq.logout().then(() => {
console.log('logout success');
}).catch(error => {
console.log(error);
});
}
wechatLogin(){
let scope = "snsapi_userinfo",
state = "_" + (+new Date());
Wechat.auth(scope, state, function (response) {
// you may use response.code to get the access token.
alert(JSON.stringify(response));
}, function (reason) {
alert("Failed: " + reason);
});
}
weiboLogin(){}
FBLogin(){
this.fb.login(['email', 'public_profile']).then((response: FacebookLoginResponse) => {
this.fb.api('me?fields=id,name,email,first_name,picture.width(360).height(360).as(picture_large)', []).then(profile => {
this.userData.login({email: profile['email'], first_name: profile['first_name'], picture: profile['picture_large']['data']['url'], username: profile['name']});
});
});
}
}

how do I create a modal view in ionic 2?

The documentation shows you how to open the modal, but isn't clear on what kind of page you're supposed to be passing to the open() method
example from docs:
import { Component } from '#angular/core';
import { ModalController, ViewController } from 'ionic-angular';
constructor(public modalCtrl: ModalController) {
}
presentContactModal() {
let contactModal = this.modalCtrl.create(ContactUs);
contactModal.present();
}
It isn't clear how where the 'ContactUs' object comes from, there is no import for it.
This example linked to here: https://ionicframework.com/docs/api/components/modal/ModalController/
import { Component } from '#angular/core';
import { ModalController, ViewController } from 'ionic-angular';
#Component(...)
class HomePage {
constructor(public modalCtrl: ModalController) { }
presentContactModal() {
let contactModal = this.modalCtrl.create(ContactUs);
contactModal.present();
}
}
///////////////below is the Contact us component which is define with in Homepage
#Component(...)
class ContactUs {
constructor(public viewCtrl: ViewController) {
}
dismiss() {
this.viewCtrl.dismiss();
}
}
The easiest way is to generate a modal content page:
ionic g ModalPage
Then you have to open modal-content.module.ts if the command creates this file, you have to change
imports: [
IonicModule.forChild(ModalPage),
],
TO :
imports: [
IonicModule.forRoot(ModalPage),
],
Then you have to add some html for the modal structure:
<ion-header>
<ion-toolbar>
<ion-title>
GO OUT
</ion-title>
<ion-buttons start>
<button ion-button (click)="dismiss()">
<span ion-text color="primary" showWhen="ios">Cancel</span>
<ion-icon name="md-close" showWhen="android,windows"></ion-icon>
</button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content>
<p> This is a modal test!!!! </p>
</ion-content>
Then you have to import in the declarations and entryComponents of the app module.
import { ModalPage } from '../pages/modal-page/modal-page';
#NgModule({
declarations: [
MyApp,
HomePage,
Main,
ModalPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
HttpModule
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
ModalPage
],
providers: [
StatusBar,
SplashScreen,
Device,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
Then in the page you want to execute the modal you have to add a function to the element you want to use to fire it.
<div full large class="button-el btn-goOut" (tap)="openModal()">
In the page you want to use the modal you have to import :
import { ModalPage } from '../modal-page/modal-page'
Important: this element should not be in the constructor, to call the modal you only have to do like this:
openModal(){
let modal = this.modalCtrl.create(ModalPage);
modal.present();
}
You can find a working example here in the docs repository.
It isn't clear how where the 'ContactUs' object comes from, there is
no import for it.
ContactUs is just another page, you can use any page from your app to create a modal with it.
import { Component } from '#angular/core';
import { ModalController, Platform, NavParams, ViewController } from 'ionic-angular';
#Component({
templateUrl: 'template.html'
})
export class BasicPage {
constructor(public modalCtrl: ModalController) { }
openModal(characterNum) {
let modal = this.modalCtrl.create(ModalContentPage, characterNum);
modal.present();
}
}
#Component({
template: `
<ion-header>
<ion-toolbar>
<ion-title>
Description
</ion-title>
<ion-buttons start>
<button ion-button (click)="dismiss()">
<span ion-text color="primary" showWhen="ios">Cancel</span>
<ion-icon name="md-close" showWhen="android, windows"></ion-icon>
</button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-list>
<ion-item>
<ion-avatar item-left>
<img src="{{character.image}}">
</ion-avatar>
<h2>{{character.name}}</h2>
<p>{{character.quote}}</p>
</ion-item>
<ion-item *ngFor="let item of character['items']">
{{item.title}}
<ion-note item-right>
{{item.note}}
</ion-note>
</ion-item>
</ion-list>
</ion-content>
`
})
export class ModalContentPage {
character;
constructor(
public platform: Platform,
public params: NavParams,
public viewCtrl: ViewController
) {
var characters = [
{
name: 'Gollum',
quote: 'Sneaky little hobbitses!',
image: 'assets/img/avatar-gollum.jpg',
items: [
{ title: 'Race', note: 'Hobbit' },
{ title: 'Culture', note: 'River Folk' },
{ title: 'Alter Ego', note: 'Smeagol' }
]
},
{
name: 'Frodo',
quote: 'Go back, Sam! I\'m going to Mordor alone!',
image: 'assets/img/avatar-frodo.jpg',
items: [
{ title: 'Race', note: 'Hobbit' },
{ title: 'Culture', note: 'Shire Folk' },
{ title: 'Weapon', note: 'Sting' }
]
},
{
name: 'Samwise Gamgee',
quote: 'What we need is a few good taters.',
image: 'assets/img/avatar-samwise.jpg',
items: [
{ title: 'Race', note: 'Hobbit' },
{ title: 'Culture', note: 'Shire Folk' },
{ title: 'Nickname', note: 'Sam' }
]
}
];
this.character = characters[this.params.get('charNum')];
}
dismiss() {
this.viewCtrl.dismiss();
}
}
In the example below, ModalContentPage is used to create the modal. Please notice that it's recommended to include just one component per file, so ideally you'd create the page to use as a modal in a different file.