Why not showing liked icon when page refresh in ionic - ionic-framework

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.

Related

Rest web service returns null value on mobile device but works on PC in Ionic App

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

Ionic 4 swipeable tabs give error when swiping

In my angular app want to make tabs swipable .I am using directive and module in directive i am defined onTabInitialized method and calling in tabs.page.ts but it not working it gives error-> ERROR TypeError: Cannot read property 'onTabInitialized' of undefined. How to solve this problem plese help me..
swipe-tab.directive.ts
import { Directive, ElementRef, Output, EventEmitter, OnInit, Renderer2, OnDestroy } from '#angular/core';
import 'hammerjs';
#Directive({
selector: '[appSwipeTab]'
})
export class SwipeTabDirective implements OnInit, OnDestroy {
#Output() tabChange = new EventEmitter();
private currentTabIndex = 0;
private tabCount = 0;
private swipeCoords: [number, number];
private swipeDuration: number;
private browserSwipeGesture: HammerManager;
private touchListenersFns = [];
tabNames: String[] = [];
constructor(
public _el: ElementRef,
private _renderer: Renderer2
) {
console.log('[SwipeTabDirective] constructor');
}
ngOnInit() {
const tabsList = this._el.nativeElement.querySelectorAll('ion-tab-button');
for (let i = 0, len = tabsList.length; i < len; i += 1) {
this.tabNames.push(tabsList[i].tab);
}
this.tabCount = this.tabNames.length - 1;
console.log('[SwipeTabDirective] ngOnInit, tabNames: ', this.tabNames);
}
onTabInitialized(tabName: string): void {
console.log('[SwipeTabDirective] onTabInitialized, tabName: ', tabName);
this.currentTabIndex = this.tabNames.indexOf(tabName);
const currentTabName = `app-${tabName}`;
const elem = this._el.nativeElement.querySelectorAll(currentTabName)[0];
if (!elem) {
throw new Error('Make sure tab selector has app prefix');
} else {
const content = elem.getElementsByTagName('ion-content')[0];
if (content.querySelector('.swipe-area') === null) {
console.log('[SwipeTabDirective] adding swipe area');
this.createWrapperDiv(content);
}
}
}
createWrapperDiv(content: HTMLElement): void {
const divElement = this._renderer.createElement('div');
this._renderer.addClass(divElement, 'swipe-area');
this._renderer.insertBefore(content, divElement, null);
while (content.children.length > 1) {
const child = content.children[0];
this._renderer.removeChild(content, child);
this._renderer.appendChild(divElement, child);
}
this.addEventListeners(divElement);
}
addEventListeners(divElement: HTMLElement) {
if ('ontouchstart' in document.documentElement) {
this.touchListenersFns.push(
this._renderer.listen(divElement, 'touchstart', ($event) => {
this.deviceSwipeHandler($event, 'start');
}),
this._renderer.listen(divElement, 'touchend', ($event) => {
this.deviceSwipeHandler($event, 'end');
})
);
} else {
this.browserSwipeGesture = new Hammer(divElement);
this.browserSwipeGesture.on('swipe', (event) => {
this.browserSwipeHandler(event);
});
}
}
deviceSwipeHandler(event: TouchEvent, status: string): void {
console.log('[SwipeTabDirective] deviceSwipeHandler, status: ', status);
const coords: [number, number] = [event.changedTouches[0].pageX, event.changedTouches[0].pageY];
const time = new Date().getTime();
if (status === 'start') {
this.swipeCoords = coords;
this.swipeDuration = time;
} else if (status === 'end') {
const direction = [coords[0] - this.swipeCoords[0], coords[1] - this.swipeCoords[1]];
const duration = time - this.swipeDuration;
if (duration < 1000 && Math.abs(direction[0]) > 50
&& Math.abs(direction[0]) > Math.abs(direction[1] * 3)) {
if (direction[0] > 0) {
this.moveBackward();
} else {
this.moveForward();
}
}
}
}
browserSwipeHandler(event) {
console.log('[SwipeTabDirective] browserSwipeHandler, direction: ', event.direction);
switch (event.direction) {
case 2:
this.moveForward();
break;
case 4:
this.moveBackward();
break;
default:
break;
}
}
moveForward(): void {
console.log('[SwipeTabDirective] moveForward');
if (this.currentTabIndex < this.tabCount) {
this.currentTabIndex++;
this.tabChange.emit(this.tabNames[this.currentTabIndex]);
}
}
moveBackward(): void {
console.log('[SwipeTabDirective] moveBackward');
if (this.currentTabIndex > 0) {
this.currentTabIndex--;
this.tabChange.emit(this.tabNames[this.currentTabIndex]);
}
}
ngOnDestroy() {
if (this.touchListenersFns.length > 0) {
this.touchListenersFns.forEach(fn => fn());
} else if (this.browserSwipeGesture) {
this.browserSwipeGesture.off('swipe');
}
}
}
also make a module for export the directives which code show in below..
directives.module.ts
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { SwipeTabDirective } from './swipe-tab.directive';
#NgModule({
declarations: [SwipeTabDirective],
imports: [
CommonModule
],
exports: [
SwipeTabDirective
]
})
export class DirectivesModule { }
The directive function use in tabs.page.ts and import directives module in tabs.page.ts
tabs.page.ts
import { Component, ViewChild } from '#angular/core';
import { IonTabs } from '#ionic/angular';
import { SwipeTabDirective } from '../directives/swipe-tab.directive';
#Component({
selector: 'app-tabs',
templateUrl: 'tabs.page.html',
styleUrls: ['tabs.page.scss']
})
export class TabsPage {
#ViewChild(SwipeTabDirective) swipeTabDirective: SwipeTabDirective;
#ViewChild('myTabs') tabRef: IonTabs;
constructor() { }
ionTabsDidChange($event) {
console.log('[TabsPage] ionTabsDidChange, $event: ', $event);
this.swipeTabDirective.onTabInitialized($event.tab);
}
onTabChange($event) {
console.log('[TabsPage] onTabChange, $event: ', $event);
this.tabRef.select($event);
}
}
In tabs.page.html i am define two function ionTabsDidChange and onTabChange ...
tabs.page.html
<ion-tabs appSwipetab (ionTabsDidChange)="ionTabsDidChange($event)" (tabChange)="onTabChange($event)" #myTabs>
<ion-tab-bar slot="bottom">
<ion-tab-button tab="tab1">
<ion-icon name="flash"></ion-icon>
<ion-label>Tab One</ion-label>
</ion-tab-button>
<ion-tab-button tab="tab2">
<ion-icon name="apps"></ion-icon>
<ion-label>Tab Two</ion-label>
</ion-tab-button>
<ion-tab-button tab="tab3">
<ion-icon name="send"></ion-icon>
<ion-label>Tab Three</ion-label>
</ion-tab-button>
</ion-tab-bar>
</ion-tabs>
I did some change in swipe-tab.directive.ts
from
const currentTabName = `app-${tabName}`;
to
const currentTabName = `${tabName}`;
and the error has gone.

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

Angular 2 Reactive form + directive validation

I'm trying to wrap my head around the following problem:
I have a 'google-place-autocomplete' directive that adds the autocomplete functionality to an input field.
Now I also wanted it to be able to force a google place selection and only be 'valid' if the user has selected a place.
E.g:
#Directive({
selector: '[googlePlace][formControlName], [googlePlace][ngModel]',
providers: [{provide: NG_VALIDATORS, useExisting: GooglePlaceDirective, multi: true}]
})
export class GooglePlaceDirective implements Validator, OnChanges {
valid = false;
#Output() googlePlaceAddressChange: any = new EventEmitter();
#Input() googlePlaceAddress: any;
#Output() ngModelChange: any = new EventEmitter();
private autocomplete: any;
constructor(private googleMapService: GoogleMapsService,
private element: ElementRef,
private zone: NgZone) {
}
ngOnInit() {
let self = this;
this.googleMapService
.load()
.subscribe(
() => {
this.autocomplete = new google.maps.places.Autocomplete(this.element.nativeElement);
this.autocomplete.addListener('place_changed', function () {
self.placeChanged(this.getPlace());
});
}
);
}
private placeChanged(place) {
this.zone.run(() => {
this.googlePlaceAddress = {
address: this.element.nativeElement.value,
formattedAddress: place.formatted_address,
latitude: place.geometry.location.lat(),
longitude: place.geometry.location.lng()
};
this.valid = true;
this.googlePlaceAddressChange.emit(this.googlePlaceAddress);
this.ngModelChange.emit(this.element.nativeElement.value);
});
}
ngOnChanges(changes): void {
let googlePlaceDefined = typeof (changes.googlePlaceAddress) !== 'undefined';
let modelDefined = typeof (changes.ngModel) !== 'undefined';
if(modelDefined && !googlePlaceDefined) {
this.valid = false;
} else if(googlePlaceDefined && !modelDefined) {
this.valid = true;
}
}
validate(control: AbstractControl) {
return this.valid === false ? {'googlePlaceAddress': true} : null;
}
}
If I use this directive in an template driven form:
...
<input name="addr" type="text" [(ngModel)]="textValue" [(googlePlaceAddress)]="googleAddress" required>
<p *ngIf="addr.errors.googlePlaceAddress">Please select a proposed address</p>
...
it works fine.
Now I need to use this in an Reactive Form using FormGroup
let groups = [
new FormControl('', [Validators.required])
];
/** HTML **/
...
<input [id]="addr"
[formControlName]="address"
class="form-control"
type="text"
googlePlace
[placeholder]="question.label"
[(googlePlaceAddress)]="googleAddress">
...
However in this case the validation from the directive is never triggered.
I suppose angular2 expects it to be given through, when using Reactive Forms:
new FormControl('', [Validators.required, ???])
I must have taken a wrong path somewhere.
For future reference:
I solved my problem creating a component out of it together with a Value accessor:
#Component({
selector: 'app-google-place',
templateUrl: './google-place.component.html',
styleUrls: ['./google-place.component.scss'],
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => GooglePlaceComponent),
multi: true
}
]
})
export class GooglePlaceComponent implements OnInit, ControlValueAccessor {
#ViewChild('inputElement') inputElement: ElementRef;
#Input() public placeholder: string = "Address";
#Input() public textValue: string = "";
private autocomplete: any;
private _place = null;
constructor(
private googleMapService: GoogleMapsService,
private zone: NgZone
) {
}
ngOnInit() {
this.googleMapService
.load()
.subscribe(
() => {
this.autocomplete = new google.maps.places.Autocomplete(this.inputElement.nativeElement);
this.autocomplete.addListener('place_changed', () => this.placeChanged());
}
);
}
placeChanged() {
this.zone.run(() => {
let place = this.autocomplete.getPlace();
this._place = {
address: this.inputElement.nativeElement.value,
formattedAddress: place.formatted_address,
latitude: place.geometry.location.lat(),
longitude: place.geometry.location.lng()
};
this.propagateChange(this._place);
});
}
onNgModelChange($event) {
if(this._place !== null) {
if(this._place.address !== $event) {
this._place = null;
this.propagateChange(this._place);
}
}
}
onBlur() {
this.propagateTouched();
}
writeValue(obj: any): void {
if(obj !== undefined) {
this._place = obj;
}
}
propagateChange = (_: any) => {};
registerOnChange(fn) {
this.propagateChange = fn;
}
propagateTouched = () => {};
registerOnTouched(fn: any): void {
this.propagateTouched = fn;
}
}
Using this I can use it in a FormGroup with the Validators.required and it will only be valid if a user has selected a google place.
EDIT
The html:
<input type="text"
(blur)="onBlur()"
#inputElement
class="form-control"
[(ngModel)]="textValue"
(ngModelChange)="onNgModelChange($event)">
The service:
import {Injectable} from '#angular/core';
import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
#Injectable()
export class GoogleMapsService {
private key = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
private loaded = false;
private currentRequest = null;
constructor() {
}
load() {
if (this.loaded) {
return Observable.create((observer) => {
observer.next();
observer.complete();
});
}
if (this.currentRequest === null) {
//http://reactivex.io/rxjs/manual/overview.html#multicasted-observables
const source = Observable.create((observer) => {
this.loadMaps(observer);
});
const subject = new Subject();
this.currentRequest = source.multicast(subject);
this.currentRequest.connect();
}
return this.currentRequest;
}
private loadMaps(observer: any) {
const script: any = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?key=' + this.key + '&libraries=places';
if (script.readyState) { // IE, incl. IE9
script.onreadystatechange = () => {
if (script.readyState == 'loaded' || script.readyState == 'complete') {
script.onreadystatechange = null;
this.loaded = true;
observer.next();
observer.complete();
this.currentRequest = null;
}
};
} else {
script.onload = () => { // Other browsers
this.loaded = true;
observer.next();
observer.complete();
this.currentRequest = null;
};
}
script.onerror = () => {
observer.error('Unable to load');
this.currentRequest = null;
};
document.getElementsByTagName('head')[0].appendChild(script);
}
}
The 'usage':
With template ngModel
<app-google-place ([ngModel)]="place"></app-google-place>

no valid session found,must call init and login before logout

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){}
}