SQLite plugin and Ionic Framework not working on real device - ionic-framework

I have a simple app that needs to store name and email.
I have installed cordova-sqlite-storage with:
ionic cordova plugin add cordova-sqlite-storage
and it works fine on the emulator.
As soon as I deploy it on the device with:
ionic cordova run android --device
I get:
plugin_not_installed
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'executeSql' of undefined
TypeError: Cannot read property 'executeSql' of undefined
at main.js:443
at new t (polyfills.js:3)
at UsersProvider.webpackJsonp.56.UsersProvider.getTotalUser (main.js:442)
at main.js:164
at t.invoke (polyfills.js:3)
at Object.onInvoke (vendor.js:5085)
at t.invoke (polyfills.js:3)
at r.run (polyfills.js:3)
at polyfills.js:3
at t.invokeTask (polyfills.js:3)
at c (polyfills.js:3)
at c (polyfills.js:3)
at polyfills.js:3
at t.invokeTask (polyfills.js:3)
at Object.onInvokeTask (vendor.js:5076)
at t.invokeTask (polyfills.js:3)
at r.runTask (polyfills.js:3)
at o (polyfills.js:3)
at e.invokeTask (polyfills.js:3)
at i.isUsingGlobalCallback.invoke (polyfills.js:3)
This is my "home.ts"
import { UsersProvider } from './../../providers/users/users';
import { SyncPage } from './../sync/sync';
import { Component } from '#angular/core';
import { NavController, AlertController, LoadingController, ModalController, Platform } from 'ionic-angular';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
newUser: any = {
first_name: '',
last_name: '',
email: '',
gdpr: false
};
totalRegistered: number = 0;
lastSync = 'mai';
loading = null;
constructor(
public navCtrl: NavController,
private alertCtrl: AlertController,
private loadingCtrl: LoadingController,
private modalCtrl: ModalController,
private platform: Platform,
private userProvider: UsersProvider
) {}
ionViewDidLoad() {
this.platform.ready().then(()=>{
this.userProvider.getTotalUser().then((data)=>{
this.totalRegistered = data;
});
});
}
add() {
this.loading = this.loading = this.loadingCtrl.create({
content: 'Registrazione in corso',
enableBackdropDismiss: true
});
this.loading.present();
this.userProvider.addUser(this.newUser).then((data) =>{
var message = 'Non è stato possibile aggiungere l\'utente.';
if(data){
message = "Utente aggiunto correttamente";
this.totalRegistered++;
}
this.loading.dismiss();
this.alertCtrl.create({
message: message,
buttons: ['Ok']
}).present();
this.clear();
});
}
clear() {
this.newUser.first_name = '';
this.newUser.last_name = '';
this.newUser.email = '';
this.newUser.gdpr = false;
}
onOpenSync(){
this.modalCtrl.create(SyncPage).present();
}
checkEmail() {
let regex = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (this.newUser.email.length > 0 && !regex.test(this.newUser.email)) {
this.alertCtrl.create({
message: "L'indirizzo email non è valido.",
buttons: ['Ok']
}).present();
}
}
}
and this is the provider:
import { Injectable } from '#angular/core';
import { SQLite, SQLiteObject } from '#ionic-native/sqlite';
#Injectable()
export class UsersProvider {
public db: SQLiteObject;
constructor(private sqlite: SQLite) {
this.sqlite.create({
name: 'apritimoda.db',
location: 'default'
}).then((db: SQLiteObject) => {
this.db = db;
db.executeSql('create table if not exists users(id INTEGER PRIMARY KEY AUTOINCREMENT, first_name VARCHAR(64), last_name VARCHAR(64), email VARCHAR(64), gdpr INT(1), synced INT(1) DEFAULT 0 )', [])
.then(() => console.log('Executed SQL'))
.catch(e => console.log(e));
}).catch(e => {
console.log('DB non trovato: -->' + e);
})
}
findUser(email:string){
return new Promise<Boolean>((resolve, reject) => {
this.db.executeSql('SELECT email FROM users WHERE email=?', [email])
.then(res => {
var found = true;
if(res.rows.length == 0){
found = false;
}
console.log('AM: utente esiste? '+found);
resolve(found);
})
.catch(e => {
console.log('AM: errore verifica email');
reject(e);
})
});
}
addUser(user:any){
return new Promise((resolve,reject) =>{
this.findUser(user.email).then((userExists) =>{
if(!userExists){
this.db.executeSql('INSERT INTO users (id, first_name, last_name, email, gdpr) VALUES (NULL, ?,?,?,?)', [
user.first_name,
user.last_name,
user.email,
user.gdpr,
])
.then(res => {
console.log('AM: utente aggiunto');
resolve(true);
})
.catch(e => {
console.log(e);
console.log('AM: errore creazione utente');
reject(false);
})
}
});
});
}
getTotalUser(){
return new Promise<number>((resolve,reject)=>{
this.db.executeSql('SELECT count(id) as total FROM users', [])
.then(res => {
var totalRegistered = 0;
if(res.rows.legth != 0){
totalRegistered = res.rows.item(0).total;
}
resolve(totalRegistered);
})
.catch(e =>{
console.log('AM: Errore ->'+ JSON.stringify(e));
reject(e);
});
});
}
getUserToSync(){
return new Promise<any[]>((resolve, reject) => {
this.db.executeSql('SELECT * FROM users WHERE synced = 0', [])
.then(res => {
var contacts = []
if(res.rows.length > 0){
for(var i=0; i<res.rows.length; i++) {
contacts.push({
id:res.rows.item(i).id,
first_name:res.rows.item(i).first_name,
last_name:res.rows.item(i).last_name,
email:res.rows.item(i).email,
gdpr:res.rows.item(i).gdpr,
});
}
}
resolve(contacts);
})
.catch(err => {
console.log('Error: '+err);
reject(err)
})
})
}
markAsSynced(ids){
if(ids.length > 0) {
var prepareQuery = "UPDATE users SET synced=1 WHERE id IN ("+this.prepareQuery(ids.length)+")";
this.db.executeSql(prepareQuery, ids)
.then(res => {
console.log(JSON.stringify(res));
})
.catch(e => {
console.log(JSON.stringify(e));
});
}
}
prepareQuery(ids){
var placeholders = [];
for(var i=0; i<ids; i++){
placeholders.push('?');
}
return placeholders.join();
}
}
Here the plugin installed:
<plugin name="cordova-plugin-whitelist" spec="1.3.3" />
<plugin name="cordova-plugin-statusbar" spec="2.4.2" />
<plugin name="cordova-plugin-device" spec="2.0.2" />
<plugin name="cordova-plugin-splashscreen" spec="5.0.2" />
<plugin name="cordova-plugin-ionic-webview" spec="^3.0.0" />
<plugin name="cordova-plugin-ionic-keyboard" spec="^2.0.5" />
<plugin name="cordova-plugin-network-information" spec="2.0.1" />
<plugin name="cordova-sqlite-storage" spec="3.2.0" />
<engine name="android" spec="7.1.4" />
Looks like that the getTotalUser is called before the DB creation in ionViewDidLoad function in home.ts.
What am I missing?

Did you install the plugin this way?
$ ionic cordova plugin add cordova-sqlite-storage
$ npm install #ionic-native/sqlite
then try this code
export class UsersProvider {
public db: SQLiteObject;
constructor(private sqlite: SQLite) {
platform.ready().then(() => {
StatusBar.styleDefault();
let db = new SQLite();
db.openDatabase({
name: "data.db",
location: "default"
}).then(() => {
db.executeSql("CREATE TABLE ....)", {}).then((data) => {
console.log("TABLE CREATED: ", data);
}, (error) => {
console.error("Unable to execute sql", error);
})
}, (error) => {
console.error("Unable to open database", error);
});
});
}
}

Call DB creation in the app.module.ts
in provider add the following function
createAndOpenDb(){
this.sqlite.create({
name: 'apritimoda.db',
location: 'default'
}).then((db: SQLiteObject) => {
this.db = db;
db.executeSql('create table if not exists users(id INTEGER PRIMARY KEY AUTOINCREMENT, first_name VARCHAR(64), last_name VARCHAR(64), email VARCHAR(64), gdpr INT(1), synced INT(1) DEFAULT 0 )', [])
.then(() => console.log('Executed SQL'))
.catch(e => console.log(e));
}).catch(e => {
console.log('DB non trovato: -->' + e);
})
}
then call that function in the app.module.ts
userProvider.createAndOpenDb()

Related

ionic upload file / capacitor / file path / readasArrayBuffer

HELP :Ionic /i'm trying to upload files to firebase but i can't read the content of the file help enter image description here
import { Component } from '#angular/core';
import { File} from '#ionic-native/file/ngx';
import { FileChooser } from '#ionic-native/file-chooser/ngx';
import { FilePath } from '#ionic-native/file-path/ngx';
import { FireBaseService } from 'src/app/services/firebase-service.service';
import { Plugins, FilesystemDirectory, FilesystemEncoding } from '#capacitor/core';
const { Filesystem } = Plugins;
#Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
fileforSending ;
fileUri :string;
filePath :string;
fileName :string;
fileType :string;
entry;
constructor(
private fireService:FireBaseService,
private fileChooser:FileChooser,
private file :File,
private pathConverter :FilePath) {
}
choose(){
this.fileChooser.open()
.then(uri => {
//getting URI of a choosen file
this.fileUri = uri;
return this.file.resolveLocalFilesystemUrl(this.fileUri);
}).then(fileEntry => {
this.entry = fileEntry;
this.entry.file((arg) => {
//getting mime type of a file
this.fileType = arg.type;
})
}).then(() => {
return this.pathConverter.resolveNativePath(this.fileUri)
}).then((filePath) => {
//converting file URI to normal file PATH & file NAME
this.filePath = filePath.substring(0, filePath.lastIndexOf('/'));
this.fileName = filePath.substring(filePath.lastIndexOf('/'), filePath.length).replace("/", "");
}).then(async () => {
try {
const buffer = await this.file.readAsArrayBuffer(this.filePath, this.fileName);
await this.fireService.uploadFileToStorage(buffer, this.fileType, this.fileName);
} catch (error) {
alert(`Buffering failed ${JSON.stringify(error)}`)
} finally {
alert('finally');
}
}).catch(err => {console.log('error: ', err) });
}
}
<!-- begin snippet: js hide: false console: true babel: false -->
--------------------------firebase service-----------------------
import { Injectable } from '#angular/core';
import {AngularFireStorage} from "#angular/fire/storage";
#Injectable({
providedIn: 'root'
})
export class FireBaseService {
constructor(private af: AngularFireStorage){}
async uploadFileToStorage(file, type, name) {
const randomId = Math.random()
.toString(36)
.substring(2, 8);
let oMyBlob = new Blob([file], {type : type})
const uploadTask = this.af.upload(`files/${new Date().getTime()}_${randomId}_${name}`,oMyBlob);
console.log('upload task '+uploadTask)
uploadTask.then(async res => {
console.log('file upload finished!');
}).catch(err => {
console.log('file wasnt upload. Error: ' + err);
});
}
}
export { FireBaseService as ExportedClass };
import { Injectable } from '#angular/core';
import {AngularFireDatabase} from "#angular/fire/database";
import {AngularFireStorage} from "#angular/fire/storage";
#Injectable({
providedIn: 'root'
})
export class FireBaseService {
constructor(private af: AngularFireStorage){}
async uploadFileToStorage(file, type, name) {
const randomId = Math.random()
.toString(36)
.substring(2, 8);
let oMyBlob = new Blob([file], {type : type})
const uploadTask = this.af.upload(
`files/${new Date().getTime()}_${randomId}_${name}`,
oMyBlob
);
uploadTask.then(async res => {
console.log('file upload finished!');
}).catch(err => {
console.log('file wasnt upload. Error: ' + err);
});
}
}
export { FireBaseService as ExportedClass };

How to set and get values of this form in local storage

I'm setting up a local storage for settings form , and want to set and get each value of that form in local storage of my application. What i need to add to make set and get correctly for this form?
everyone can see that the get results has error and mabe the set is not done correctly.
How to make all of that work
do i need to change set and get methods? is there anythin that i am missing ? i tried all i know but i am a beginner in local storage and ionic .
my file ts :
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular.min.js"></script>
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { FormBuilder, FormGroup, Validators, NgForm, FormControl, ValidatorFn, AbstractControl } from '#angular/forms';
import { ToastController } from 'ionic-angular';
import { EspaceAgentPage } from '../espace-agent/espace-agent';
import { EspaceCitoyenPage } from '../espace-citoyen/espace-citoyen';
import { ChangePasswordPage } from '../change-password/change-password';
import { Storage } from '#ionic/storage';
import { PasswordService } from '../services/password.service';
import { NgModule } from '#angular/core';
#Component({
selector: 'page-settings',
templateUrl: 'settings.html',
})
export class SettingsPage {
private Form : FormGroup;
public mail: any;
public tel: any;
public data: any;
constructor(public navCtrl: NavController, public navParams: NavParams, public toastCtrl: ToastController, private formBuilder: FormBuilder, public storage: Storage)
{
this.Form = formBuilder.group({
mailadress: ['', Validators.compose([Validators.pattern('^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$'),Validators.email])],
telephone: ['', Validators.compose([ Validators.pattern('[0-9]*'), Validators.minLength(8), Validators.maxLength(8)])],
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad SettingsPage');
this.getValue("stoker");
}
// set a key/value
setValue(key: string, value: any)
{
this.storage.set(key, value).then((response) => {
console.log('set' + key + ' ', response);
}).catch((error) => {
console.log('set error for ' + key + ' ', error);
});
}
// get a key/value pair
getValue(key: string) {
this.storage.get(key).then((val) => {
console.log('get ' + key + ' ', val);
this.data[key] = "";
this.data[key] = val;
}).catch((error) => {
console.log('get error for ' + key + '', error);
});
}
onChangepassword()
{
this.navCtrl.push(ChangePasswordPage);
}
onSubmit(form: NgForm)
{
this.mail=this.Form.get('mailadress').value;
this.tel=this.Form.get('telephone').value;
console.log(form.value);
this.setValue("stoker",this.mail);
this.setValue("stoker",this.tel);
this.navCtrl.push(EspaceCitoyenPage);
const toast = this.toastCtrl.create({
message: 'Modifications Enregistrées !',
duration: 4000
});
toast.present();
}
}
console results capture :
capture
it seems that you get the error in this funtion
// get a key/value pair
getValue(key: string) {
this.storage.get(key).then((val) => {
console.log('get ' + key + ' ', val);
this.data[key] = "";
this.data[key] = val;
}).catch((error) => {
console.log('get error for ' + key + '', error);
});
}
when you try to get stoker key returns a null reference and then the error. Maybe there is not item stored for this key or the palform was not ready when you call the storage.
When you work arround the storage you shoud wait from the platform to be ready like this:
import { Platform } from '#ionic/angular';
import { NativeStorage } from '#ionic-native/native-storage/ngx';
-----
constructor(private storage: NativeStorage, private plt: Platform) {}
this.plt.ready().then(() => {
// call native storage
});
And think is better use Native Storage than ionic storage.
Hope this help you.
plsease refer this
import { NativeStorage } from '#ionic-native/native-storage/ngx';
constructor(private nativeStorage: NativeStorage) { }
import { NativeStorage } from '#ionic-native/native-storage/ngx';
constructor(private nativeStorage: NativeStorage) { }
this.nativeStorage.setItem('myitem', {property: 'value', anotherProperty: 'anotherValue'})
.then(
() => console.log('Stored item!'),
error => console.error('Error storing item', error)
);
this.nativeStorage.getItem('myitem')
.then(
data => console.log(data),
error => console.error(error)
);
this.nativeStorage.setItem('myitem', {property: 'value', anotherProperty: 'anotherValue'})
.then(
() => console.log('Stored item!'),
error => console.error('Error storing item', error)
);
this.nativeStorage.getItem('myitem')
.then(
data => console.log(data),
error => console.error(error)
);
localstorage.setitem('your key as your wish',your value),
all storage value are stored in string
ex;-
localstorage.setitem('key', value)
localstorage.getitem('key')
You can use
Windows.localstorage.setitem('key', value)

How to get OneSignal Push Notification Device ID Ionic 3

I have implemented the push notification functionality in my ionic app but it is not working. I am not getting the register id after the app is deployed. Following is my code.
app.component.ts
constructor(public platform: Platform, public splashScreen: SplashScreen, public menu: MenuController,
private storage: StorageService,private toast: ToastService, public events: Events, private push: Push,
private alertCtrl: AlertController, public network: Network, private api: UserService) {
platform.ready().then(() => {
debugger
this.pushSetup();
this.userDetails = this.storage.getData('userDetails');
this.isAlertShown = false;
// this.task = setInterval(() => {
// this.checkInternet();
// }, 3000);
if (this.userDetails != undefined || this.userDetails != null) {
this.rootPage = 'welcome';
} else {
this.rootPage = 'login';
}
this.initializeApp();
});
pushSetup() {
console.log("inside pushSetup");
const options: PushOptions = {
android: {
senderID: '592660866764',
forceShow: 'true'
},
ios: {
alert: 'true',
badge: true,
sound: 'false'
}
};
console.log("inside pushSetup 1");
const pushObject: PushObject = this.push.init(options);
pushObject.on('notification').subscribe((notification: any) => console.log('Received a notification', notification));
pushObject.on('registration').subscribe((registration: any) =>console.log('Received a notification', registration));
pushObject.on('error').subscribe(error => console.error('Error with Push plugin', error));
}
Install the Cordova and Ionic Native plugins:
ionic cordova plugin add onesignal-cordova-plugin
npm install --save #ionic-native/onesignal
insert in app.module.ts Onesignal
import { OneSignal } from '#ionic-native/onesignal';
providers: [
....
OneSignal
...
]
In App Component you needs One Signal App ID and Google Project ID
in app.component.ts:
import { OneSignal } from '#ionic-native/onesignal';
import { Platform } from 'ionic-angular';
constructor(public oneSignal: OneSignal,
private platform: Platform) { }
onseSignalAppId: string = 'YOUR_ONESIGNAL_APP_ID';
googleProjectId: string = 'YOUR_GOOGLE_PROJECT_ID';
if(this.platform.is('cordova')) {
if (this.platform.is('android')) {
this.oneSignal.startInit(this.onseSignalAppId, this.googleProjectId);
}
else if (this.platform.is('ios')) {
this.oneSignal.startInit(this.onseSignalAppId);
}
this.oneSignal.inFocusDisplaying(this.oneSignal.OSInFocusDisplayOption.Notification);
this.oneSignal.handleNotificationReceived().subscribe(() => {
// do something when notification is received
});
this.oneSignal.handleNotificationOpened().subscribe(result => {
// do something when a notification is opened
});
this.oneSignal.endInit();
// AND THIS METHOD RETURN YOUR DEVICES USER_ID
this.oneSignal.getIds().then(identity => {
alert(identity.pushToken + ' it's PUSHTOKEN');
alert(identity.userId + 'it's USERID);
});
}

The record is added without data, but it is null - Angular

The record is added without data, but it is null - Angular 5 and Mongodb ^3.0.1
http://localhost:3000/api/users
{
"status":200,
"data":[
{
"_id":"5a63f4da17fc7e9e5548da70",
"name":"Jonson Doeal",
"password":"password"
},
{
"_id":"5a63faf417fc7e9e5548da71",
"name":"Jonson Bol",
"password":"password"
},
{
"_id":"5a64f44de87b3e2f80437c6b",
"name":"aaaa",
"password":"aaaa"
},
{
"_id":"5a67e03bb1d1941d7451c0fa",
"name":null,
"password":"Highway 37"
}
],
"message":null
}
server/routes/api.js:
const express = require('express');
const router = express.Router();
const MongoClient = require('mongodb').MongoClient;
const ObjectID = require('mongodb').ObjectID;
// Connect 27017
const connection = (closure) => {
return MongoClient.connect('mongodb://localhost:27017/mean', (err, client) => {
if (err) return console.log(err);
let db = client.db('mean');
closure(db);
});
};
// Error handling
const sendError = (err, res) => {
response.status = 501;
response.message = typeof err == 'object' ? err.message : err;
res.status(501).json(response);
};
// Response handling
let response = {
status: 200,
data: [],
message: null
};
// Get users
router.get('/users', (req, res) => {
connection((db) => {
db.collection('users')
.find()
.toArray()
.then((users) => {
response.data = users;
res.json(response);
})
.catch((err) => {
sendError(err, res);
});
});
});
router.post("/users", (req, client) =>{
const myobj = { name: req.body.userName, password: "Highway 37" };
connection((db) => {
db.collection('users').insertOne(myobj, (err, doc) =>{
});
});
});
module.exports = router;
req.body.userName ----> is null :
{"_id":"5a67e03bb1d1941d7451c0fa","name":null,"password":"Highway
37"}],"message":null}
db.collection('users').insertOne( req.body, (err, doc) =>{ } ---> it does not add any values :
{"_id":"5a689b767803052e00e76ded"}],"message":null}
auth/auth.service.ts:
import {Injectable} from '#angular/core';
import {Router} from '#angular/router';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import {User} from './user';
import {Http, Headers, RequestOptions, Response} from '#angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class AuthService {
private loggedIn = new BehaviorSubject<boolean>(false);
result: any;
get isLoggedIn() {
return this.loggedIn.asObservable();
}
constructor(private router: Router, private _http: Http) {}
registration(newUser: User): Promise<void | User> {
return this._http.post('/api/users', newUser)
.toPromise()
.then(response => response.json().data as User);
}
getUsers() {
return this._http.get('/api/users').map(result => this.result = result.json().data);
}
}
auth/user.ts:
export interface User {
userName: string;
password: string;
}
registration/registration.ts:
<form class="example-form" (ngSubmit)="onSubmitRegistration(user)">
<mat-input-container class="full-width-input">
User * <input matInput name="user-userName" (ngModel)="user.userName" required>
</mat-input-container>
<mat-input-container class="full-width-input">
Password * <input matInput name="user-password" type="password" (ngModel)="user.password" required>
</mat-input-container>
<mat-card-footer>
<button mat-raised-button color="primary" type="submit">Zapisz</button>
</mat-card-footer>
<br />
</form>
registration/registration.component.ts:
import {AuthService} from './../auth/auth.service';
import {Component, OnInit, Input} from '#angular/core';
import {FormGroup, FormBuilder, Validators} from '#angular/forms';
import {User} from '../auth/user';
#Component({
selector: 'app-registration',
templateUrl: './registration.component.html',
styleUrls: ['../login/login.component.css']
})
export class RegistrationComponent implements OnInit {
private formSubmitAttempt: boolean;
errorMessage: string;
#Input()
user: User;
#Input()
createHandler: Function;
constructor(private fb: FormBuilder, private authService: AuthService) {}
ngOnInit() {}
onSubmitRegistration(user: User) {
this.authService.registration(user).then((newUser: User) => {
this.createHandler(newUser);
console.log('onSubmitRegistration ' + newUser);
});
}
}
Does this method 'onSubmitRegistration' send correctly values? The console does not display a message :
console.log('onSubmitRegistration ' + newUser);
How to correctly add data to the database?
solution:
the data was badly sent to the server
registration/registration.component.ts:
<form class="example-form" [formGroup]="registrationForm" (ngSubmit)="onSubmitRegistration()">
User * <input matInput formControlName="userName" required>
Password * <input matInput type="password" formControlName="password" required>
<button mat-raised-button color="primary" type="submit">Zapisz</button>
</form>
registration/registration.component.ts:
registrationForm: FormGroup;
// ...
onSubmitRegistration(user: User) {
this.authService.registration(this.registrationForm.value);
}
auth/auth.service.ts:
registration(newUser: User): Promise<User> {
return this._http.post('/api/users', newUser)
.toPromise()
.then(response => response.json().data as User);
}

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">