what is wrong in my storage implementation ionic 2 app? - ionic-framework

i'm trying to save data in local storage in ionic 2 app so i
import the storage and did exactly like i saw in the website and it not save the data in the storage
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 {
pages: Array<{title: string, component: any}>;
photo:any;
constructor(public navCtrl: NavController,public storage:Storage) {
}
ionViewDidLoad() {
this.getDetailsFacebook();
}
getDetailsFacebook() {
var that=this;
Facebook.getLoginStatus().then((response)=> {
if (response.status == 'connected') {
Facebook.api('/' + response.authResponse.userID + '?fields=id,name,gender', []).then((response)=> {
that.uid = response.id;
that.photo = "http://graph.facebook.com/"+that.uid+"/picture?type=large";
that.storage.set('photo',that.photo');
//console.log("id:"+this.uid+this.name+this.photo);
}, (error)=> {
alert(error);
})
}
else {
alert('Not Logged in');
}
})
photo of the inspect with chrome developer
i don't see any key of photo as i set it.. why is that?

Installation
To use this in your Ionic 2/Angular 2 apps, either start a fresh Ionic project which has it installed by default, or run:
npm install #ionic/storage
If you'd like to use SQLite as a storage engine, install a SQLite plugin (only works while running in a simulator or on device):
cordova plugin add cordova-sqlite-storage --save
In order to use Storage you may have to edit your NgModule declaration in src/app/app.module.ts to add Storage as a provider as below:
import { Storage } from '#ionic/storage';
#NgModule({
declarations: [
...
],
imports: [
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
...
],
providers: [ Storage ] // Add Storage as a provider
})
export class AppModule {}
Now, you can easily inject Storage into a component:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Storage } from '#ionic/storage';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController, public storage: Storage) {
}
}
To set an item, use Storage.set(key, value):
this.storage.set('name', 'Mr. Ionitron');
To get the item back, use Storage.get(name).then((value) => {}) since get() returns a Promise:
this.storage.get('name').then((name) => {
console.log('Me: Hey, ' + name + '! You have a very nice name.');
console.log('You: Thanks! I got it for my birthday.');
});
For more info on Storage module refer link: https://github.com/driftyco/ionic-storage

Related

deep links not working - ionic

im using deeplinks and ionic 3, but the url i created not working.
this is the url : https://lucky.com/prd/rm74fEgBB2frzhagYcov
this is my code :
this.deepLinks.route({
'/prd/:id': ProductDetailsPage,
'/rcm/:id': RecommendationDetailsPage
})
.subscribe((match) => {
console.log(match);
}, (nomatch) => {
console.log(nomatch);
});
he doesnt go to the subscribe function, either nor to the match or nomatch
what is my problem ?
Please check this
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 {Deeplinks} from '#ionic-native/deeplinks';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage: string = 'DashboardPage';
#ViewChild(Nav) nav: Nav;
constructor(public platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen,
private deeplinks: Deeplinks) {
platform.ready().then(() => {
statusBar.styleDefault();
splashScreen.hide();
if (platform.is('cordova')) {
this.deeplinks.routeWithNavController(this.nav, {
'/event/:year/:month/:eventItem/:title': 'ScheduleDetails',
'/email/verify/': 'Login',
'/password/reset/:token': 'ChangePassword',
'/prd/:id': 'ProductDetailsPage',
'/rcm/:id': 'RecommendationDetailsPage'
}).subscribe((match) => {
// console.log('success' + JSON.stringify(match));
}, (noMatch) => {
// alert('error' + JSON.stringify(noMatch));
// console.log('error' + JSON.stringify(noMatch));
});
}
});
}
}
And don't forgot to add providers as Deeplinks in app.module.ts file

Ionic 3 OneSignal Push Notification Click Open Page

I use OneSignal Push Notification for Ionic 3 . I want to when click notification application open page.
My app.component.ts
import { Component, ViewChild } from '#angular/core';
import { Platform, NavController } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { OneSignal } from '#ionic-native/onesignal';
import { DuyurularPage } from '../pages/duyurular/duyurular';
#Component({
templateUrl: 'app.html',
providers:[OneSignal],
template: '<ion-nav #myNav [root]="rootPage"></ion-nav>'
})
export class MyApp {
rootPage:any = 'MenuPage';
bgColor: string = '#fff';
#ViewChild('myNav') nav: NavController;
constructor(platform: Platform, statusBar: StatusBar, splashScreen:
SplashScreen, private oneSignal: OneSignal,) {
platform.ready().then(() => {
statusBar.styleDefault();
splashScreen.hide();
window["plugins"].OneSignal
.startInit("**************", "***********")
.handleNotificationOpened()
.handleNotificationReceived()
.endInit();
});
this.oneSignal.handleNotificationOpened().subscribe((jsonData) => {
alert(JSON.stringify(jsonData));
this.nav.push(DuyurularPage);
});
this.oneSignal.handleNotificationReceived().subscribe((jsonData) =>
{
alert(JSON.stringify(jsonData));
this.nav.push(DuyurularPage);
});
}
}
When I do mistake I don' t know. Notification coming but not show alert or not push DuyurularPage, just open homepage.
if you Need to Open a Specific page on Notification Tapped. Follow the technique.
In App.component.ts
this.oneSignal.handleNotificationOpened().subscribe((data) => {
// do something when a notification is opened
console.log('Tapped',data);
if(data.notification.payload.additionalData.landing_page != undefined && data.notification.payload.additionalData.landing_page != ''){
this.PushProvider.landing_page = data.notification.payload.additionalData.landing_page;
}
if(data.notification.payload.additionalData.product_id != undefined && data.notification.payload.additionalData.product_id != ''){
this.PushProvider.product_id = data.notification.payload.additionalData.product_id;
}
});
this.oneSignal.endInit();
//On Home Page
if(this.PushProvider.landing_page != undefined){
console.log('on home if',this.PushProvider.landing_page);
this.navCtrl.push('offerzonePage',{ from_tab: this.PushProvider.landing_page});
}
if(this.PushProvider.product_id != undefined){
console.log('on home if',this.PushProvider.product_id);
this.navCtrl.push('ProductPage',{ product_id: this.PushProvider.product_id });
}
On Pushprovicer.ts
import { Injectable } from '#angular/core';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class PushProvider {
// Produc ID
product_id: any;
// Landing pages
landing_page: any;
}
can you use the below syntax and try;
import { Component, ViewChild } from '#angular/core';
import { Platform, NavController } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { OneSignal } from '#ionic-native/onesignal';
import { DuyurularPage } from '../pages/duyurular/duyurular';
#Component({
templateUrl: 'app.html',
providers:[OneSignal],
template: '<ion-nav #myNav [root]="rootPage"></ion-nav>'
})
export class MyApp {
rootPage:any = 'MenuPage';
bgColor: string = '#fff';
#ViewChild('myNav') nav: NavController;
constructor(platform: Platform, statusBar: StatusBar, splashScreen:
SplashScreen, private oneSignal: OneSignal,) {
platform.ready().then(() => {
statusBar.styleDefault();
splashScreen.hide();
this.oneSignal.startInit('*****', '***');
this.oneSignal.inFocusDisplaying(this.oneSignal.OSInFocusDisplayOption.InAppAlert);
this.oneSignal.handleNotificationOpened().subscribe((jsonData) => {
alert(JSON.stringify(jsonData));
this.nav.push(DuyurularPage);
});
this.oneSignal.handleNotificationReceived().subscribe((jsonData) =>
{
alert(JSON.stringify(jsonData));
});
}
You cannot use NavController in app.component.ts it seems.
Can you use Nav or App
What I would do is create an obsevable and subscribe to it anywhere needed in my app. The observable will emit its next value whenever the plugin callback is fired.
RxJS Observable
Emit next value on callback
Subscribe anywhere in your app
Use provided NavCtrl to push a component into the view
The same principle would work if you inject ionic's Event.
Btw you have a random comma at the end of your constructor

passing parameter between pages ionic

Hi i´m new in ionic and I am trying to pass the scann information form one page to another, the thing its that when I execute the program I have a console.log to check if the info its passed correctly but on chrome console said undefined, letme paste my code:
home.ts where i try to send the info from the scan:
import { Component } from '#angular/core';
import { NavController,Platform } from 'ionic-angular';
import { BarcodeScanner } from '#ionic-native/barcode-scanner';
import { TabsPage } from '../tabs/tabs';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
private barcodeText:String;
private barcodeFormat:String;
private platform:Platform;
private navController:NavController;
constructor(private barcodeScanner: BarcodeScanner,public navCtrl: NavController,platform:Platform) {
this.platform = platform;
this.navController = navCtrl;
}
doScan(){
console.log('scannig product barcode');
this.platform.ready().then(() => {
this.barcodeScanner.scan().then((result) => {
if (!result.cancelled) {
this.barcodeText = result.text;
this.scanningDone(this.barcodeText)
}
}, (error) => {
console.log('error when scanning product barcode');
});
});
}
scanningDone(data){
this.navController.push(TabsPage,{
data:data
});
}
main.ts where the info suppose to go:
import { Component } from '#angular/core';
import { NavController, NavParams , ToastController} from 'ionic-angular';
import { BarcodeScanner } from '#ionic-native/barcode-scanner';
import { DetailsPage } from '../details/details';
import { Http } from '#angular/http'
#Component({
selector: 'main',
templateUrl: 'main.html'
})
export class MainPage {
information: any[];
item:any;
private bcData;
constructor(public navCtrl: NavController, private http: Http,public params:NavParams) {
this.bcData = params.get('data');
console.log(params.get('data'));
let localData = http.get(this.bcData).map(res => res.json().items);
localData.subscribe(data => {
this.information = data;
})
}
on the console.log(params.get('data')); its where I get the undefinied on the console.
you could have a method in your TabsPage that handles opening and closing pages like this:
openPages(Page, Data){
this.navCtrl.push(Page,Data);
}
Then in your scanningDone Method:
scanningDone(data){
this.tabsPage.openPages(MainPage,{
data:data
});
}
How about using localStorage
look at this as well

Assigning an import to a variable within a constructor

I am building an app in Ionic2. I want to implement Facebook within the app and so I am trying to use the ionic-native Facebook api. I imported it and then attempted to assign it to a variable so I could use the functions associated with it.
Here is my code.
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Facebook } from 'ionic-native';
#Component({
selector: 'page-news-feed',
templateUrl: 'news-feed.html',
})
export class NewsFeed {
fb: any;
constructor(public navCtrl: NavController, facebook: Facebook) {
this.fb = facebook;
}
doRefresh(refresher) {
console.log('Begin async operation', refresher);
setTimeout(() => {
console.log('Async operation has ended');
refresher.complete();
}, 2000);
}
this.fb.login([]);
ionViewDidLoad() {
console.log('Hello NewsFeed Page');
}
}
I thought an import works much like a class in that you can import it and assign it to a variable and then have access to its methods. Does it not work like that? How does it work?
You just have to import Facebook class like it is said in Ionic native docs :
https://ionicframework.com/docs/v2/native/
You don't need to inject it through the constructor. As method are static this will print an error.
Be sure to also call Facebook after platform.ready event. And don't forget to add the plugin. See your example modified accordingly.
import { Component } from '#angular/core';
import { NavController, Platform } from 'ionic-angular';
import { Facebook } from 'ionic-native';
#Component({
selector: 'page-news-feed',
templateUrl: 'news-feed.html',
})
export class NewsFeed {
constructor(public navCtrl: NavController, platform: Platform) {
platform.ready().then(() => {
console.log('Faceboook');
Facebook.login([]).then((response) => {
console.log(response);
}).catch((error) => {
console.error(error);
});
})
}
doRefresh(refresher) {
console.log('Begin async operation', refresher);
setTimeout(() => {
console.log('Async operation has ended');
refresher.complete();
}, 2000);
}
ionViewDidLoad() {
console.log('Hello NewsFeed Page');
}
}

Firebase returns AUTHENTICATION_DISABLED [duplicate]

I am creating a simple sample auth app with Ionic 2 and angularfire 2 as backend, when i try to create new user it says:
EXCEPTION: Error: Uncaught (in promise): Error: The specified
authentication provider is not enabled for this Firebase.
But i already enabled firebase authentication in firebase console:
app.ts
import {App, Platform} from 'ionic-angular';
import {StatusBar} from 'ionic-native';
import {HomePage} from './pages/home/home';
import { FIREBASE_PROVIDERS, defaultFirebase, firebaseAuthConfig, AuthProviders, AuthMethods } from 'angularfire2';
#App({
template: '<ion-nav [root]="rootPage"></ion-nav>',
providers: [
FIREBASE_PROVIDERS,
defaultFirebase('https://samplequizapp-50eb5.firebaseio.com'),
firebaseAuthConfig({
provider: AuthProviders.Password,
method: AuthMethods.Password
})
],
config: {} // http://ionicframework.com/docs/v2/api/config/Config/
})
export class MyApp {
rootPage: any = HomePage;
constructor(platform: Platform) {
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();
});
}
}
home.ts
import { Page } from 'ionic-angular';
import { AngularFire, FirebaseListObservable } from 'angularfire2';
import { OnInit } from '#angular/core'
#Page({
templateUrl: 'build/pages/home/home.html'
})
export class HomePage implements OnInit {
user: any = {};
data: FirebaseListObservable<any[]>;
constructor(private af: AngularFire) {
}
ngOnInit() {
this.data = this.af.database.list('/userId')
}
signUp(data) {
this.af.auth.createUser({
email: data.email,
password: data.password
})
}
}
I am pretty sure there is nothing wrong with my code:
Firebase2 in its current version (2.4.2) is not yet compatible with Firebase SDK v3, and all projects created with the new Firebase console are only accessible with calls comaptible with SDK v3.
You want to create your Firebase backend in the legacy console www.firebase.com first, and then migrate to the new console.
This is documented in this closed issue of the angularfire2 github: https://github.com/angular/angularfire2/issues/189