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">
Related
i am consuming Rest JSONP Web Service in an ionic App which works fine on PC but returns null value on mobile devices
My page.ts file
import {
Component,
OnInit
} from '#angular/core';
import {
AlertController,
LoadingController
} from '#ionic/angular';
import {
ActionSheetController
} from '#ionic/angular';
import {
Router
} from '#angular/router'
import {
ProApiService
} from './../../../../services/pro-api.service';
#Component({
selector: 'app-ranked-diagnosis',
templateUrl: './ranked-diagnosis.page.html',
styleUrls: ['./ranked-diagnosis.page.scss'],
})
export class RankedDiagnosisPage implements OnInit {
tabSelect: string = 'show10';
show10Data: Array < any >= [];
showAllData: Array < any >= [];
redFlagsData: Array < any >= [];
loading: any;
constructor(
private api: ProApiService,
public alertController: AlertController,
public loadingController: LoadingController,
public actionSheetController: ActionSheetController,
private router: Router
) {}
segmentChanged(event: any) {
this.tabSelect = event.detail.value;
}
async presentActionSheet(buttons) {
const actionSheet = await this.actionSheetController.create({
header: 'Sub Diagnosis',
buttons: buttons
});
await actionSheet.present();
}
async presentAlert(msg: string, header: string) {
const alert = await this.alertController.create({
header: '',
subHeader: header,
message: msg,
buttons: ['OK']
});
await alert.present();
}
async presentLoading() {
this.loading = await this.loadingController.create({
message: 'loading...',
});
return await this.loading.present();
}
ngOnInit() {
}
ionViewWillEnter() {
if (this.api.ProApiData.diagnoses_checklist.diagnoses) {
this.showAllData =
this.api.ProApiData.diagnoses_checklist.diagnoses;
for (let i = 0; i < 10; i++) {
this.show10Data.push(this.showAllData[i]);
}
this.showAllData.forEach(item => {
if (item.red_flag == 'true') {
this.redFlagsData.push(item);
}
});
console.log(this.showAllData);
} else {
console.log('error');
this.router.navigateByUrl('isabel-pro');
}
}
why_diagnosis(url: any, weightage: any) {
this.presentLoading();
this.api.why_diagnosisApi(url).subscribe(res => {
let matched_terms = res._body.why_diagnosis.matched_terms;
console.log(matched_terms);
let alertMsg = `We matched the terms: ${matched_terms}<br><hr>Degree of match between query entered and database: ${weightage}`;
this.presentAlert(alertMsg, 'Why did this diagnosis come up ?');
this.loadingController.dismiss();
}, err => {
this.loadingController.dismiss();
console.log('error');
});
}
}
in the above code i am calling why_diagnosis function which calls the function from a service file.
My service.ts file
import {
Injectable
} from '#angular/core';
import {
HttpClient,
HttpHeaders
} from '#angular/common/http';
import {
Jsonp
} from '#angular/http';
import {
Observable
} from 'rxjs';
import {
map
} from 'rxjs/operators';
import {
ConstantsService
} from './../../../services/constants.service';
#Injectable({
providedIn: 'root'
})
export class ProApiService {
apiRoot = this.root.APIroot;
diagnosisPROData: any;
drugData: any;
ProApiData: any;
drugApiData: any;
constructor(
private jsonp: Jsonp,
private http: HttpClient,
private root: ConstantsService) {}
why_diagnosisApi(url: any): Observable < any > {
let whyUrl = `${this.apiRoot}Mob_isabelPRO.php?
why_url=${url}&callback=JSONP_CALLBACK`;
return this.jsonp.request(whyUrl, 'callback')
.pipe(
map(
res => {
let why_diagnosis = res;
return why_diagnosis;
}
)
);
}
}
above code is from my service file.
this is the value i am getting in PC
this is the return on mobile
i dont know whats wrong with it. please suggest me the solution
Thanks
I am making like and dislike functionality in ionic app when user like then want to show heart icon and when user dislike then want to show empty heart icon.When like the post then icon show but when refreshing page then its show icon of empty likes.Please help me how to resolve this problem in ionic....
tab1.page.html
<div>
<img src="{{getImage.image}}" (click)="tapPhotoLike(getImage.id)" (click)="toggleIcon(getImage.id)">
</div>
<p no-margin no-padding>
<button clear ion-button icon-only class="like-btn">
<!-- <ion-icon no-padding name="like_btn.icon_name" color="{{ like_btn.color }}" class="icon-space"></ion-icon> -->
<ion-icon name="heart-empty" *ngIf="!iconToggle[getImage.id]" color="{{ like_btn.color }}"></ion-icon>
<ion-icon name="heart" *ngIf="iconToggle[getImage.id]" color="{{ like_btn.color }}"></ion-icon>
</button>
</p>
tab1.page.ts
import { Component, OnInit } from '#angular/core';
import { UserService } from '../user.service';
import { User } from '../user';
import { first } from 'rxjs/operators';
import { Storage } from '#ionic/storage';
import { ToastController } from '#ionic/angular';
import { LoadingController, NavController } from '#ionic/angular';
#Component({
selector: 'app-tab1',
templateUrl: 'tab1.page.html',
styleUrls: ['tab1.page.scss']
})
export class Tab1Page implements OnInit {
num
getImages: User[] = [];
getImages2: User[] = [];
getImages3 = [];
getcounts;
countLikes
counts
unlikes
likesID
iconToggle = [];
like_btn = {
color: 'danger',
icon_name: 'heart-empty'
};
public tap: number = 0;
public status: false;
constructor(private userService: UserService,
public toastController: ToastController,
private storage: Storage,
public navCtrl: NavController,
public loadingController: LoadingController) {
}
doRefresh(event) {
this.userPost();
setTimeout(() => {
event.target.complete();
}, 2000);
}
ngOnInit() {
this.userPost();
//this.getCountOfLikes();
}
async userPost() {
const loading = await this.loadingController.create({
message: 'Please wait...',
spinner: 'crescent',
duration: 2000
});
await loading.present();
this.userService.getUserPost().pipe(first()).subscribe(getImages => {
this.getImages3 = getImages;
loading.dismiss();
});
}
likeButton() {
const detail_id = this.userService.getCurrentIdpostId();
this.storage.get('userId').then((val) => {
if (val) {
let user_id = val
this.userService.userPostLikes(user_id, detail_id).pipe(first()).subscribe(
async data => {
this.iconToggle[this.num] = true;
if (data['status'] === 'you have already liked this post') {
const toast = await this.toastController.create({
message: 'you have already liked this post before.',
duration: 2000
});
toast.present();
}
this.userPost();
}
);
}
});
}
tapPhotoLike($detail_id, num) {
this.userService.setCurrentIdpostId($detail_id);
this.tap++;
setTimeout(() => {
if (this.tap == 1) {
this.tap = 0;
//this.unlikePost();
} if (this.tap > 1) {
this.tap = 0;
}
}, 250);
}
setIconToggles() {
let x = 0;
this.getImages3.forEach(() => {
this.iconToggle[x] = false;
x++;
});
}
toggleIcon(num) {
if (this.iconToggle[num]) {
this.iconToggle[num] = false;
this.unlikePost();
} else {
this.iconToggle[num] = true;
this.likeButton();
}
}
ionViewWillEnter() {
this.userPost();
}
unlikePost() {
let detail_id = this.userService.getCurrentIdpostId();
this.storage.get('userId').then((val) => {
if (val) {
let user_id = val;
this.userService.unLikes(user_id, detail_id).subscribe(async dislikes => {
this.unlikes = dislikes;
this.iconToggle[this.num] = false;
this.userPost();
})
}
});
}
}
How manage icon , i am inserting status on like and dislike in database..In this code how to manage status please help me.
I want to retrieve places coordinates from restApi and display them on the map.
I got error : Cannot read property 'length' of undefined
Please help me !
I want you to tell me how i can get my data in order to add multiple markers.
This is my portion of code
import { Component, ViewChild, ElementRef } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Geolocation } from '#ionic-native/geolocation';
import { RestProvider } from '../../providers/rest/rest';
declare var google;
#Component({
selector: 'page-localisation',
templateUrl: 'localisation.html',
})
export class LocalisationPage {
#ViewChild('map') mapElement: ElementRef;
map: any;
places: Array<any>;
errorMessage : string;
constructor(public navCtrl: NavController, public navParams: NavParams, public geolocation: Geolocation, public rest: RestProvider) {
}
ionViewDidLoad(){
this.loadMap();
this.getPlaces();
this.addPlacesToMap()
console.log("Length : " + this.places.length) ; //Error Cannot read property 'length' of undefined
}
getPlaces() {
this.rest.getPlaces().subscribe(
places => this.places = places,
error => this.errorMessage = <any>error
);
}
loadMap(){
let latLng = new google.maps.LatLng(-4.066548, 5.356315);
let mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
}
addPlacesToMap(){
//...
}
addInfoWindow(marker, content){
let infoWindow = new google.maps.InfoWindow({
});
content: content
google.maps.event.addListener(marker, 'click', () => {
infoWindow.open(this.map, marker);
});
}
}
ionViewDidLoad is launched before "this.rest.getPlaces().subscribe" is finished... So your variable "places" is NULL
Change getPlaces to a Promise
async getPlaces() {
places = await this.rest.getPlaces() ;
return places
}
Then in ionViewDidLoad
ionViewDidLoad(){
var that = this ;
this.loadMap();
this.getPlaces().then((places)=>{
that.places = places;
console.log("Length : " + that.places.length) ;
});
this.addPlacesToMap()
}
I have a typescript file with this part of code:
export class HomePage {
createprofile = {} as CreateProfile;
profileData: FirebaseObjectObservable<CreateProfile>;
constructor(private afAuth: AngularFireAuth, private toast: ToastController, private afDatabase: AngularFireDatabase, public navCtrl: NavController) {
}
goToYourItemsListPage(){
this.navCtrl.setRoot("YourItemsListPage");
}
ionViewDidLoad() {
this.afAuth.authState.take(1).subscribe(data => {
if(data && data.email && data.uid){
this.profileData = this.afDatabase.object(`create-profile/${data.uid}`);
//console.log(data);
}else{
this.toast.create({
message: `Could not find authentication details!`,
duration: 3000,
position: "bottom"
}).present();
}
});
}
}
And in home.html I am adding this code:
<h1>Welcome, {{(profileData | async)?.firstName}}!</h1>
But it is not displaying error nor any value it's just: "Welcome !"
What am I missing here?
I'm a newbie to ionic.
Thank you
I only have login via facebook in my ionic 2 app. I installed cordova pluginfor that with this code
`ionic plugin add cordova-plugin-facebook4 --variable APP_ID="123456789" --variable APP_NAME="myApplication"`
Sometimes I see this message pop up on my app:
no valid session found,must call init and login before logout
and my app crashes. Below is a screenshot:
I have already tried to delete the app and install it again but the issue still persists.
this is my facebook login
Facebook.login(['email']).then( (response) => {
let facebookCredential = firebase.auth.FacebookAuthProvider
.credential(response.authResponse.accessToken);
var that = this;
firebase.auth().signInWithCredential(facebookCredential)
.then((success) => {
that.nav.setRoot(HomePage);
})
.catch((error) => {
console.log("Firebase failure: " + JSON.stringify(error));
});
}).catch((error) => { console.log(error) });
}
get details from facebook
//facebook functions
getDetailsFacebook() {
var that=this;
Facebook.getLoginStatus().then((response)=> {
if (response.status == 'connected') {
Facebook.api('/' + response.authResponse.userID + '?fields=id,name,gender', []).then((response)=> {
//alert(JSON.stringify(response));
that.uid = response.id;
that.name=response.name;
that.photo = "http://graph.facebook.com/"+that.uid+"/picture?type=large";
that.user=new User(that.uid,that.fireUid,that.name, that.photo);
that.profileData.setProfileData(that.user); // to create class for that
//that.profileData.setProfile(that.uid,that.name,that.photo);
//console.log("id:"+this.uid+this.name+this.photo);
}, (error)=> {
alert(error);
})
}
else {
alert('Not Logged in');
}
})
log out function
logOutFacebook(){
Facebook.logout().then((response)=>
{
this.navCtrl.push(LoginPage);
alert(JSON.stringify(response));
},(error)=>{
alert(error);
})
}
home.html
<ion-header>
<ion-navbar color="pinka">
<ion-title></ion-title>
<ion-buttons start (click)="addNote()">
<button ion-button>
<ion-icon name="add-circle"></ion-icon>
</button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content padding class="padiHome">
<ion-avatar>
<img src={{photo}}>
<h1>{{name}}</h1>
</ion-avatar>
<ion-list>
<ion-item-sliding *ngFor="let note of notes">
<ion-item [ngStyle]="{'background-color':'note.color'}">
<h2>{{note.title}}</h2>
<p>{{note.desc}} + {{note.color}}</p>
</ion-item>
<ion-item-options side="left" style="direction:ltr">
<button ion-button="secondary" (click)="update(note.id)">
<ion-icon name="create"></ion-icon>
edit
</button>
<button ion-button="danger" (click)="delete(note.id)">
<ion-icon name="trash"></ion-icon>
delete
</button>
</ion-item-options>
</ion-item-sliding>
</ion-list>
<button ion-button (click)="logOutFacebook()">log Out</button>
</ion-content>
home.ts
import { Component } from '#angular/core';
import { NavController,NavParams,LoadingController,AlertController,ViewController } from 'ionic-angular';
import { Facebook } from 'ionic-native';
//import pages
import {LoginPage} from "../../pages/login/login";
import {User} from '../../models/user'
import { Storage} from '#ionic/storage';
//import provider
import { ProfileData } from '../../providers/profile-data';
import { NotesData } from '../../providers/notes-data';
import firebase from 'firebase'
import {AddNote} from "../add-note/add-note";
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
//facebook user
userProfile: any = null;
uid: any = null;
fireUid:any=null;
name:string=null;
photo: any = null;
user:User=null;
photos:any=null;
currentUser:any=null;
//notes list
notes:any=null;
data:any;
constructor(public navCtrl: NavController, public navParams: NavParams,public profileData:ProfileData,private viewCtrl: ViewController,public notesData:NotesData,private loadingCtrl: LoadingController,private alertCtrl: AlertController,public storage:Storage) {
this.data={};
this.data.title="";
this.data.desc="";
}
ionViewDidLoad() {
console.log("home");
this.fireUid=firebase.auth().currentUser.uid;
this.currentUser=firebase.auth().currentUser;
this.storage.get('photo').then( (value:any) => {
this.photo=value;
});
this.storage.get('name').then( (value:any) => {
this.name=value;
});
//this.getDetailsFacebook();
this.getNotesList();
}
//facebook functions
getDetailsFacebook() {
var that=this;
Facebook.getLoginStatus().then((response)=> {
if (response.status == 'connected') {
Facebook.api('/' + response.authResponse.userID + '?fields=id,name,gender', []).then((response)=> {
//alert(JSON.stringify(response));
that.uid = response.id;
that.name=response.name;
that.photo = "http://graph.facebook.com/"+that.uid+"/picture?type=large";
that.user=new User(that.uid,that.fireUid,that.name, that.photo);
that.profileData.setProfileData(that.user); // to create class for that
//that.profileData.setProfile(that.uid,that.name,that.photo);
//console.log("id:"+this.uid+this.name+this.photo);
}, (error)=> {
alert(error);
})
}
else {
alert('Not Logged in');
}
})
/*this.photo=firebase.database().ref('users/'+this.currentUser+'/photos').on('value',snapshot=>{
var that=this;
that.photonew=snapshot.val().id;
})
*/
}
}
logOutFacebook(){
Facebook.logout().then((response)=>
{
this.navCtrl.push(LoginPage);
alert(JSON.stringify(response));
},(error)=>{
alert(error);
})
}
//notes functions
getNotesList(){
console.log("get event");
var that=this;
this.notesData.getNotesLIst().on('value', snapshot => {
let notesList= [];
snapshot.forEach( snap => {
console.log("id note"+snap.val().id);
notesList.push({
id: snap.val().id,
title: snap.val().title,
desc: snap.val().desc,
color:snap.val().color,
});
});
that.notes = notesList;
});
}
addNotes() {
let prompt = this.alertCtrl.create({
//title: 'הכנס פתק',
cssClass:'noteAlert',
message: "הכנס פתק תיאור",
inputs: [
{
name: 'title',
placeholder: 'כותרת'
},
{
name: 'desc',
placeholder: 'פרטים'
},
],
buttons: [
{
text: 'ביטול',
handler: data => {
console.log('Cancel clicked');
}
},
{
text: 'הוסף',
handler: data => {
this.data.title=data.title;
this.data.desc=data.desc;
//this.notesData.createNote(this.data.title, this.data.desc);
console.log('פתק נשמר');
}
}
]
});
prompt.present();
console.log(this.data.title, this.data.desc);
}
addNote(){
this.navCtrl.push(AddNote);
}
delete(id:number){
}
update(id:number){}
}