updating form ion-select in Ionic - ionic-framework

I want to perform an update in an ion-select but I can't. My level of programming is very low and there are still many things that I don't understand.
The options are read from a table ('categories') that has two fields ('id', 'name') through the getAllCategories() method, but I can't get the value of the 'name' field that is already assigned to it to be displayed
I do a search for the category with its corresponding Id with the getCategory(1) method (I have put a 1, because I don't know how to search through a variable) but it does not appear selected (where it says 'Select Category') despite I think I'm sending the data correctly, because it appears in the console.log
update-recipe.page.html
<ion-item lines="full">
<ion-select id="category" name="category" placeHolder="Select Category" (ionChange)="ObtenerCategoryId($event)">
<ion-select-option *ngFor="let category of categories" value="{{category.id}}">{{category.name}}</ion-select-option>
</ion-select>
</ion-item>
<form [formGroup]="updateRecipeForm" (ngSubmit)="onSubmit()" novalidate>
<ion-item lines="full">
<ion-label position="floating">Tittle</ion-label>
<ion-input formControlName="tittle" type="text" required></ion-input>
</ion-item>
<!-- <span class="error ion-padding" *ngIf="isSubmitted && errorControl.name.errors?.required">Tittle is required.</span> -->
<ion-item lines="full">
<ion-label position="floating">Description</ion-label>
<ion-input formControlName="description" type="text" required></ion-input>
</ion-item>
<!-- <span class="error ion-padding" *ngIf="isSubmitted && errorControl.description.errors?.required">Description is required.</span> -->
<ion-row>
<ion-col>
<ion-button type="submit" color="primary" expand="block">Update</ion-button>
</ion-col>
</ion-row>
</form>
update-crecipe.page.ts
export class Recipe {
id: number;
tittle: string;
description: string;
filename: string;
userId: number;
categoryId: number;
}
#Component({
selector: "app-update-recipe",
templateUrl: "./update-recipe.page.html",
styleUrls: ["./update-recipe.page.scss"],
})
export class UpdateRecipePage implements OnInit {
categories: any =[];
categoryId: any;
updateRecipeForm: FormGroup;
isSubmitted = false;
id: any;
capturedPhoto = '';
// eslint-disable-next-line #typescript-eslint/no-inferrable-types
imageSaved: string = '';
constructor(
private recipeService: RecipeService,
private categoryService: CategoryService,
private activatedRoute: ActivatedRoute,
private formBuilder: FormBuilder,
private router: Router,
private photoService: PhotoService,
private storage: Storage
) {
this.id = this.activatedRoute.snapshot.paramMap.get('id');
}
ionViewWillEnter(){
this.findRecipe(this.id);
this.updateRecipeForm = this.formBuilder.group({
tittle: [''],
description: [''],
filename: [''],
categoryId: ['']
});
this.capturedPhoto = '';
}
ngOnInit() {
this.findRecipe(this.id);
this.updateRecipeForm = this.formBuilder.group({
tittle: [''],
description: [''],
filename: [''],
categoryId: ['']
},
);
this.capturedPhoto = '';
// this.updateRecipeForm.reset();
this.getCategory(1);
this.getAllCategories();
}
async findRecipe(id) {
let token = await this.storage.get("token");
this.recipeService.getRecipe(this.id, token).subscribe(async data => {
this.imageSaved = data['filename'];
this.updateRecipeForm.setValue({
tittle: data['tittle'],
description: data['description'],
filename: data['filename'],
categoryId: data ['categoryId']
});
});
}
async ObtenerCategoryId(e){
console.log("valor obtenido"+e.detail.value);
let categoryId = await this.storage.set("categoryId_st", e.detail.value);
}
async getCategory(id) {
let token = await this.storage.get("token");
this.categoryService.getCategory(id, token).subscribe(async res => {
console.log(res);
this.categories = res;
}, error => {
console.log(error);
console.log("User not authenticated. Please log in");
this.router.navigateByUrl("/home");
});
}
async getAllCategories() {
let token = await this.storage.get("token");
this.categoryService.getCategories(token).subscribe(async res => {
console.log(res);
this.categories = res;
}, error => {
console.log(error);
console.log("User not authenticated. Please log in");
this.router.navigateByUrl("/home");
});
}
async onSubmit() {
this.isSubmitted = true;
if (!this.updateRecipeForm.valid) {
return false;
} else {
let blob = null;
if (this.capturedPhoto !== "") {
const response = await fetch(this.capturedPhoto);
blob = await response.blob();
}
(
await this.recipeService
.updateRecipe(this.id, this.updateRecipeForm.value, blob, this.getCategory(this.id)))
.subscribe(data => {
console.log('¡Photo sent!');
this.updateRecipeForm.reset();
this.router.navigate(['/you-are-logged-in']);
});
}
}

There are many typos in the code.
Secondly, you need to read the documentation if you're new. The documentation provides your answer: https://ionicframework.com/docs/api/select#object-value-references

Related

values.map is not a function Sequelize

I'm trying to send a form to my db but I get this error :
The problem XD
I have this problem only when I try to do it from the front, because when I try with Insomnia it works. So I'm not sure where the problem is coming from.
I'm using multer for the image.
The model:
const { DataTypes } = require('sequelize');
// Exportamos una funcion que define el modelo
// Luego le injectamos la conexion a sequelize.
module.exports = (sequelize) => {
// defino el modelo
sequelize.define('Recipe', {
id:{
type: DataTypes.UUID(5),
primaryKey:true,
defaultValue:DataTypes.UUIDV4(5)
},
title: {
type: DataTypes.STRING,
allowNull: false,
},
summary:{
type:DataTypes.STRING,
allowNull: false,
},
healthScore:{
type: DataTypes.INTEGER,
},
steps:{
type:DataTypes.ARRAY(DataTypes.STRING)
},
dishTypes:{
type:DataTypes.ARRAY(DataTypes.STRING)
},
readyInMinutes:{
type: DataTypes.INTEGER,
get(){
return "Ready in " + this.getDataValue("readyInMinutes") + " minutes"
}
},
ingredients:{
type: DataTypes.ARRAY(DataTypes.STRING)
},
servings:{
type:DataTypes.STRING
},
image:{
type:DataTypes.STRING,
defaultValue: `https://post.healthline.com/wp-content/uploads/2020/08/food-still-life-salmon-keto-healthy-eating-732x549-thumbnail-732x549.jpg`
}
},{
timestamps: false
});
};
The post route (actually the helper):
const createNewRecipe = require("../helpers/RecipeCont/CreateRecipe/CreateRecipe")
const createNewRecipeRoute = async (req, res) => {
try {
const data = {
title,
summary,
healthScore,
steps,
dishTypes,
readyInMinutes,
ingredients,
servings,
Diet_type,
} = req.body;
const image = req.file.path
let newRecipe = await createNewRecipe({
title,
summary,
healthScore,
steps,
dishTypes,
readyInMinutes,
ingredients,
servings,
image,
});
await newRecipe.addDiet_type(Diet_type)
console.log(req.file)
res.status(200).json("Receta creada con éxito");
} catch (error) {
console.log(error)
res.status(400).json(error.message);
}
}
module.exports = createNewRecipeRoute;
The form
import React, {useState} from "react";
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { createRecipe, getDietTypes } from "../../actions/actions";
import styles from "./form.module.css"
export default function Form(){
const [form,setForm] = useState({
title:"",
summary:"",
healthScore:0,
steps:[],
dishTypes:[],
readyInMinutes:0,
ingredients:[],
servings:0,
image:"",
Diet_type:[1]
})
const [steps, setSteps] = useState("")
const [dishTypes, setDishType]=useState("")
const [ingredients, setIngredients]= useState("")
const dispatch=useDispatch()
useEffect(()=>{
dispatch(getDietTypes())
},[])
const diets = useSelector(state=> state.diet)
const changeHandler=(e)=>{
if(e.target.name==="image"){
setForm({...form,[e.target.name]: e.target.file })
}
setForm({...form, [e.target.name]:e.target.value})
}
const stepHandler = (e)=>{
let aux = e.target.name
let auxV = e.target.value
if(e.key==="Enter"){
e.preventDefault()
setForm({...form, [e.target.name]: [...form[aux] , auxV ]})
aux==="steps"? setSteps("") : aux==="ingredients"? setIngredients("") : setDishType("")
}
console.log(form)
}
const deleteHandler = (e)=>{
let help = e.target.name
e.preventDefault()
let aux = form[help].filter(s=> s!==e.target.value)
setForm({...form, [help]: [...aux]})
}
const imageHandler = (e)=>{
setForm({...form, [e.target.name]:e.target.files[0]})
}
const sendHandler = (e)=>{
e.preventDefault();
if(form.image!==""){
const formData = new FormData()
formData.append("image",form.image)
formData.append("title",form.title)
formData.append("summary",form.summary)
formData.append("healthScore",form.healthScore)
formData.append("steps",form.steps)
formData.append("dishTypes",form.dishTypes)
formData.append("readyInMinutes",form.readyInMinutes)
formData.append("Ingredients",form.ingredients)
formData.append("servings",form.servings)
formData.append("Diet_type",form.Diet_type)
for (var key of formData.entries()) {
console.log(key[0] + ', ' + key[1]);
}
dispatch(createRecipe(formData))
} else {
dispatch(createRecipe(form))
}
console.log(form)
}
return(
<>
<div className={styles.div} >
<h2>Create your own recipe!</h2>
<form encType="multipart/form-data" method="POST" onSubmit={sendHandler}>
<div className={styles.divTitle}>
<h2>Title:</h2>
<input type="text" placeholder="Title" name="title" value={form.title} onChange={changeHandler}></input>
</div>
<input type="text" placeholder="summary" name="summary" value={form.summary} onChange={changeHandler}></input>
{form.healthScore}<input type="range" placeholder="healthScore" name="healthScore" min="1" max="100" step="1" value={form.healthScore} onChange={changeHandler} ></input>
<div>
<input type="text" name="steps" value={steps} onChange={(e)=>{setSteps(e.target.value)}} onKeyDown={stepHandler} placeholder="Steps"></input>
<div>
{form.steps.length>0? form.steps.map(e=><li>{e}<button value={e} name="steps" onClick={deleteHandler}>x</button></li>) : "Add the steps of your recipe!"}
</div>
</div>
<div>
<input type="text" name="ingredients" value={ingredients} onChange={(e)=>{setIngredients(e.target.value)}} onKeyDown={stepHandler} placeholder="Ingredients"></input>
<div>
{form.ingredients.length>0? form.ingredients.map(e=><li>{e}<button value={e} name="ingredients" onClick={deleteHandler}>x</button></li>) : "Add the ingredients of your recipe!"}
</div>
</div>
<div>
<input type="text" name="dishTypes" value={dishTypes} onChange={(e)=>{setDishType(e.target.value)}} onKeyDown={stepHandler} placeholder="Dish types"></input>
<div>
{form.dishTypes.length>0? form.dishTypes.map(e=><li>{e}<button value={e} onClick={deleteHandler}>x</button></li>) : "Add the dish types of your recipe!"}
</div>
</div>
<select>
{console.log(diets)}
{diets?.map(d=><option key={d.id} id={d.id}>{d.name}</option>)}
</select>
<input className={styles.number} name="readyInMinutes" value={form.readyInMinutes} onChange={changeHandler} type="number"></input>
<input className={styles.number} name="servings" value={form.servings} onChange={changeHandler} type="number"></input>
<input type="file" name="image" onChange={imageHandler}></input>
<input type="submit"></input>
</form>
</div>
</>
)
}
I'm still working on the form, in Diet_type for example, but even trying to hardcode the state to make the post it doesn't work.
The "for" is because the console.log doesn't work with formData and at the beginning I thought it was that I wasn't sending anything, but actually I do.
I save the image of all the request even for those which can fulfill so the middleware seems its working too.
I hope you can help me to understand what's going on and try to find a solution, c: Thanks for your time!!
The object values does not have the map methode.
You expect that there should be a map methode, but this is not a javascipt array with protype map. So you get the error.
You can use the loadash library.
const {map} require(`lodash`)
map(values, value => {
console.log(value)
// your code coes here
}

Function Query.where() requires a valid third argument, but it was undefined when trying to view the page

I'm trying to implement rating system in my shopping app, but received error console when trying to open the page.
The error on console are:
Function Query.where() requires a valid third argument, but it was undefined. - it points to:
this.stars = this.starService.getProductStars(this.movieId)
AND
const starsRef = this.afs.collection('stars', ref => ref.where('movieId', '==', movieId));
Below is my code:
rating.page.html: (where I put my 2 of components which are TestRate and Star-Review)
<ion-content>
<app-testrate></app-testrate>
<app-star-review-component></app-star-review-component>
</ion-content>
testrate.component.html:
<div *ngIf="movie | async as m">
<h1>
{{m.title}}
</h1>
<img [src]="m.image" width="100px">
<p>
{{m.plot}}
</p>
<star-review [movieId]="movieId" [userId]="userId"></star-review>
</div>
testrate.component.ts:
export class TestrateComponent implements OnInit {
userDoc: AngularFirestoreDocument<any>;
movieDoc: AngularFirestoreDocument<any>;
user: Observable<any>;
movie: Observable<any>;
constructor(private afs: AngularFirestore) { }
ngOnInit() {
this.userDoc = this.afs.doc('users/test-user-3')
this.movieDoc = this.afs.doc('movies/battlefield-earth')
this.movie = this.movieDoc.valueChanges()
this.user = this.userDoc.valueChanges()
}
get movieId() {
return this.movieDoc.ref.id
}
get userId() {
return this.userDoc.ref.id
}
}
star-review.component.html:
<h3>Average Rating</h3>
{{ avgRating | async }}
<h3>Reviews</h3>
<div *ngFor="let star of stars | async">
{{ star.userId }} gave {{ star.movieId }} {{ star.value }} stars
</div>
<h3>Post your Review</h3>
<fieldset class="rating">
<ng-container *ngFor="let num of [5, 4, 3, 2, 1]">
full star
<input (click)="starHandler(num)"
[id]="'star'+num"
[value]="num-0.5"
name="rating"
type="radio" />
<label class="full" [for]="'star'+num"></label>
half star
<input (click)="starHandler(num-0.5)"
[value]="num-0.5"
[id]="'halfstar'+num"
name="rating"
type="radio" />
<label class="half" [for]="'halfstar'+num"></label>
</ng-container>
</fieldset>
star-review.component.ts:
export class StarReviewComponentComponent implements OnInit {
#Input() userId;
#Input() movieId;
stars: Observable<any>;
avgRating: Observable<any>;
constructor(private starService: StarService) { }
ngOnInit() {
this.stars = this.starService.getProductStars(this.movieId)
this.avgRating = this.stars.pipe(map(arr => {
const ratings = arr.map(v => v.value)
return ratings.length ? ratings.reduce((total, val) => total + val) / arr.length : 'not reviewed'
}))
}
starHandler(value) {
this.starService.setStar(this.userId, this.movieId, value)
}
}
star.service.ts:
export class StarService {
constructor(private afs: AngularFirestore) { }
// Star reviews that belong to a user
getUserStars(userId) {
const starsRef = this.afs.collection('stars', ref => ref.where('userId', '==', userId));
return starsRef.valueChanges();
}
// Get all stars that belog to a Product
getProductStars(movieId) {
const starsRef = this.afs.collection('stars', ref => ref.where('movieId', '==', movieId));
return starsRef.valueChanges();
}
// Create or update star
setStar(userId, movieId, value) {
// Star document data
const star: Star = { userId, movieId, value };
// Custom doc ID for relationship
const starPath = `stars/${star.userId}_${star.movieId}`;
// Set the data, return the promise
return this.afs.doc(starPath).set(star)
}
}

Angular 5 - Updating Model from Form

i'm new to Angular 5 and i'm trying to make a CRUD.
i'm struggling with the "update" part.
what i'd want to do is, in my form, getting back the data of the Model to fill the input text with, then, when i click on the update button, updating the all model.
I tried so many thing from tuts and forums that i'm completly lost now. So here is what i have.
html :
<form [formGroup]="policyForm" (ngSubmit)="update()">
<mat-form-field>
<input formControlName="policyName">
</mat-form-field>
... Many other inputs
<button type="submit" color="primary">Update</button>
</form>
component :
export class PolicyUpdateComponent implements OnInit {
policyModel: PolicyModel;
policyId = +this.route.snapshot.paramMap.get('id');
policyForm: FormGroup;
formBuilder: FormBuilder;
constructor(
private policyService: PolicyService,
private route: ActivatedRoute,
private router: Router,
private fb: FormBuilder
) {
this.policyService.get(this.policyId)
.subscribe(policy => this.policyModel = policy);
}
ngOnInit() {
this.createForm();
}
createForm() {
this.policyForm = this.fb.group({
policyName: [this.policyModel.name, Validators.required]
});
}
update(id: number) {
id = this.policyId;
this.policyModel = <PolicyModel>this.policyForm.value;
this.policyService.update(id, this.policyModel).subscribe(res => {
this.router.navigate(['/policies', id, 'get']);
}, (e) => {
console.log(e);
}
);
}
}
service :
/**
* Update a policy with new parameters
* #param pm PolicyModel
*/
update(id: number, pm: PolicyModel): Observable<any> {
return this.http.put<PolicyModel>(`${environment.baseApiUrl}/${environment.apiVersion}/policies/${id}`, {pm});
}
any help would be nice.. thanks guys!
Change the code according to this.
<form [formGroup]="policyForm" >
<mat-form-field>
<input formControlName="policyName">
</mat-form-field>
<button color="primary" (click)="update()">Update</button>
</form>
Add subscription to detect form changes.
ngOnInit() {
this.createForm();
this.policyForm.valueChanges.subscribe(
(data) => {
if (JSON.stringify(data) !== JSON.stringify({})) {
this.policyModel.name = data.policyName;
}
});
}
createForm() {
this.policyForm = this.fb.group({
policyName: [this.policyModel.name]
});
}
update(id) {
this.policyModel.id = id;
id = this.policyId;
this.policyService.update(id, this.policyModel)//.subscribe(res => {
this.router.navigate(['/policies', id, 'get']);
}, (e) => {
console.log(e);
}
);
}
Sample code : https://stackblitz.com/edit/angular-wwt91u

can't switch status value from 0 to 1 after calling function angular

I am working on a frontend application with Angular 5 and using rest api from backend. Actually, I am developing admin platforme and I have two web pages, one for displaying list of customers and each one has list of feedbacks and one other get you to specific feedback details.
The feedback details display these properties: account, feedback itself and the loyalty point if existed.
There is two ways, if a feedback has its loyalty point then the feedback details will show details with loyalty point value else it will show empty input for this property and if the input is successful, it will return to main list with changed value of status of feedback from false to true.
I am using rest api and for this operation I successfully tested the API:
API: PATCH /Feedbacks/:id
Here is my code:
account.service.ts:
#Injectable()
export class AccountService {
constructor(private http: Http) {}
headers: Headers = new Headers({ 'Content-Type': 'application/json' });
options: RequestOptionsArgs = new RequestOptions({headers: this.headers});
// API: PATCH /Feedbacks/:id
updateStatus(feedback: Feedback) {
let url = "http://localhost:3000/api/Feedbacks";
return this.http.patch(url + feedback.id, feedback, this.options)
.map(res => res.json())
.catch(err => {
return Observable.throw(err)
});
}
}
component.html:
<form *ngIf="feedback">
<div class="form-group">
<label for="InputAccount">Account</label>
<input type="text" class="form-control" id="InputAccount" value="{{feedback.account}}">
</div>
<div class="form-group">
<label for="InputFeedback">Feedback</label>
<textarea class="form-control" id="InputFeedback" rows="3" placeholder="Feedback">{{feedback.feedback}}</textarea>
</div>
<div class="form-group">
<label for="InputLP">LP</label>
<input type="text" class="form-control" id="InputLP" placeholder="LP" [(ngModel)]="account.lp" name="lp">
</div>
<div class="form-group" *ngIf="!edited; else showBack">
<button (click)="addLP(account,feedback)" class="btn btn-primary" data-dismiss="alert">Add LP</button>
</div>
</form>
component.ts:
#Component({
selector: 'app-add',
templateUrl: './add.component.html',
styleUrls: ['./add.component.scss']
})
export class AddComponent implements OnInit {
feedback = {};
account = {};
edited:boolean;
status: boolean;
constructor(private route: ActivatedRoute, private accountService: AccountService,
private router: Router) { }
ngOnInit() {
this.route.paramMap
.switchMap((params: ParamMap) =>
this.accountService.getFeedback(+params.get('idF')))
.subscribe(feedback => this.feedback = feedback);
this.route.paramMap
.switchMap((params: ParamMap) =>
this.accountService.getAccount(params.get('idC')))
.subscribe(account => this.account = account);
}
addLP(account:Account,feedback:Feedback){
this.accountService.updateAccount(account)
.subscribe(res => {
this.account = res as Account;
console.log(res);
if (account.lp == null){
console.log(res);
this.edited = false;
} else {
this.edited = true;
this.accountService.updateStatus(feedback)
.subscribe(res => {
feedback.status = true;
this.feedback = res as Feedback;
console.log(this.feedback);
}, err => {
console.log(err);
});
}
}, err => {
console.log(err);
});
}
back() {
this.router.navigate(['list']);
}
}
the feedback property:
public id?: number,
public feedback?: string,
public account?: string,
public status?: boolean
Where the account is a foreign key to account table:
public account?: string,
public lp?: string
When I try to switch status value automatically from false to true, the console log will return:
PATCH http://localhost:3000/api/Feedbacks2 404 (Not Found)
Any help would be appreciated! I really need to solve it. Thanks
I modified the code in account.service.ts:
updateStatus(feedback: Feedback) {
let url = "http://localhost:3000/api/Feedbacks";
var body = {status: true};
return this.http.patch(url +"/"+ feedback.id, body, this.options)
.map(res => res.json())
.catch(err => {
return Observable.throw(err)
});
}
And it worked !

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