Does anyone know how to reset the "ion-option" values of "ion-select". I have two ion-select controls and i want my first ion-select(selectedPLocation) to change the values of my 2nd ion-select(selectedLocation) on ionChange. I am able to remove selected by setting null but i am not able to change the values of selectedLocation. Does anyone know how to reset the value of my ion-options ?
I'm currently using VS2015 s my IDE.
HTML:
<ion-list>
<ion-item>
<ion-label>Parent Location</ion-label>
<ion-select [(ngModel)]="selectedPLocation" (ionChange)="loadLocation()">
<ion-option *ngFor="let parentLocation of parentLocations; let i=index" [value]="parentLocation.Key">{{parentLocation.Id}}</ion-option>
</ion-select>
</ion-item>
<ion-item>
<ion-label>Location</ion-label>
<ion-select [(ngModel)]="selectedLocation">
<ion-option id="locationID" *ngFor="let location of locations; let i=index" [value]="location.Key">{{location.Id}}</ion-option>
</ion-select>
</ion-item>
</ion-list>
TypeScript:
public loadLocation() {
let loader = this.loadingCtrl.create({
content: "Please wait..."
});
loader.present();
this.selectedLocation = null; //Reset selected value only
this.locations = null; //Tried this but can't seem to reset the values
this.locationService.GetLocations(this.global.getApiUrl(), this.selectedSite, this.selectedPLocation).then(data => {
loader.dismiss();
this.locations = data;
}).catch((err) => {
loader.dismiss();
let alert = this.alertCtrl.create({
title: 'Error',
subTitle: err,
buttons: ['OK']
});
alert.present();
});}
I solved my own error, it is due to my Typescript codes call to my web service API (GetLocation).
Previous TypeScript Code:
public GetLocations(apiUrl, siteKey, pLocationKey) {
return new Promise((resolve, reject) => {
this.http.get(apiUrl + "site/" + siteKey + "/location/" + pLocationKey)
.map(res => res.json())
.subscribe(data => {
this.Locations = data; //Error Here
resolve(this.Locations);; //Error Here
},
err => {
reject(err);
});
});
}
Correct TypeScript Code:
public GetLocations(apiUrl, siteKey, pLocationKey){
return new Promise((resolve, reject) => {
this.http.get(apiUrl + "site/" + siteKey + "/location/" + pLocationKey)
.map(res => res.json())
.subscribe(data => {
resolve(data); //Corrected
},
err =>{
reject(err);
});
});
}
Related
I'm trying to login users with Facebook and Firebase, I have followed the documentation and some tutorials but I cannot make it work. I'm having this:
enter image description here
Plugin version:
"cordova-plugin-facebook4": "^6.4.0",
Also:
"cordova-plugin-facebook4": {
"APP_ID": "47**********",
"APP_NAME": "Mimas"
},**
My code:
public authWithFacebook(): Promise<any> {
return new Promise(async (resolve, reject) => {
if (this.platform.is('cordova')) {
await this.facebook.login(['public_profile']).then((res) => {
console.log(res);
const credential = firebase.auth.FacebookAuthProvider.credential(res.authResponse.accessToken);
this.afAuth.auth.signInWithCredential(credential).then(response => {
console.log(response);
resolve(response);
}).catch(err => {
console.log(err);
reject(this.translate.get(err.code));
});
}).catch(err => {
console.log("ERROR =========>");
console.log(err);
reject();
});
} else {
console.log("ELSEEEEEE =========>");
const fbprovider = new firebase.auth.FacebookAuthProvider();
this.afAuth.auth.signInWithPopup(fbprovider).then(res => {
resolve(res);
}).catch((e) => {
reject(e);
});
}
});
}
I have a parent (organisation) document in firestore and multiple child documents. I want load he data based on if the parent or child was clicked in the same component.
The below code works, the data is shown, but updates to the child organisations are not shown in real time (I have to reload to see it.). I'm guessing it is because I'm binding the array orgArray and not the object org that I actually use to display the data. Is there a way to just bind the object and not the whole array?
<template>
<div class="route-container">
<div class="item__container">
<FmisTitle/>
<Hero
:orgName="org.name"
:orgLogo="org.logo"
:orgState="org.state"
:orgNumber="org.number"
:orgType="org.type"
:orgDateStart="org.dateStart"
:orgDateEnd="org.dateEnd"
:orgDateStartF="org.dateStartFunctional"
:orgDateEndF="org.dateEndFunctional"
:orgCoverImage="org.coverImagex745"
:childRef="org.id"
:orgRef="orgRef"
/>
<Contact
:orgEmail="org.email"
:orgPhone="org.phoneNumber"
:orgAddress="org.address"
:orgWebsite="org.website"
:orgSocials="org.socials"
:childRef="org.id"
:orgRef="orgRef"
/>
<ButtonDuo/>
</div>
</div>
</template>
export default {
data() {
return {
org: {},
orgArray: [],
orgRef: '',
};
},
created() {
firebase.auth().onAuthStateChanged((user) => {
firestore.collectionGroup('people').where('userId', '==', user.uid).get().then((query) => {
query.forEach((userRef) => {
const orgRef = userRef.ref.parent.parent.id;
this.orgRef = orgRef;
if (!this.$route.params.parent) {
const organisation = firestore.collection('organisations').doc(orgRef).collection('childOrganisations').where('name', '==', this.$route.params.id);
this.$bind('orgArray', organisation).then((doc) => {
const org = doc[0];
this.org = org;
});
} else {
const organisation = firestore.collection('organisations').doc(orgRef);
this.$bind('org', organisation);
}
});
});
}, (error) => {
console.log(error);
});
},
}
I solved this by using the id from the childOrg and getting the data with that id, that way I could bind the data object directly.
firebase.auth().onAuthStateChanged((user) => {
firestore.collectionGroup('people').where('userId', '==', user.uid).get().then((query) => {
query.forEach((userRef) => {
const orgRef = userRef.ref.parent.parent.id;
this.orgRef = orgRef;
if (this.$route.query.parent !== 'true') {
firestore.collection('organisations').doc(orgRef).collection('childOrganisations').where('name', '==', this.$route.params.id)
.get()
.then((q) => {
q.forEach((ref) => {
const orgId = ref.id;
const organisation = firestore.collection('organisations').doc(orgRef).collection('childOrganisations').doc(orgId);
this.$bind('org', organisation);
});
});
} else {
const organisation = firestore.collection('organisations').doc(orgRef);
this.$bind('org', organisation);
}
});
});
}, (error) => {
console.log(error);
});
I'm trying to push data to firebase database by userId , even each user he can modify has post or has information . the pushed data is successfully , but the problem is when l am try to getting data in html dose not show .
database
html
code for getting data :
items: Observable<any[]>;
itemsRef: AngularFireList<any>;
constructor(public fire: AngularFireAuth,public db: AngularFireDatabase)
{
this.itemsRef = db.list(`report/`);
// Use snapshotChanges().map() to store the key
this.items = this.itemsRef.snapshotChanges().pipe(
map(changes =>
changes.map(c => ({ key: c.payload.key, ...c.payload.val() }))
)
);
}
html
<ion-list *ngFor="let item of items | async">
<ion-item-sliding>
<ion-item>
<h2>{{itemstitle}}</h2>
<p>{{item.name}}</p>
<p>{{item.username}}</p>
<p>{{item.dateadded}}</p>
</ion-item>
<ion-item-options side="right">
<button ion-button color="danger" (click)="deletReport(item.key)">
<ion-icon ios="ios-trash" md="md-trash" item-end large></ion-icon>
</button>
<button ion-button color="primary" (click)="updatereport(item.key,item.name,item.title)">
<ion-icon ios="ios-create" md="md-create"></ion-icon>
</button>
</ion-item-options>
</ion-item-sliding>
</ion-list>
my push data :
name :string='';
title :string='';
Email:string='';
dateadded:string='';
userId: string;
reports: AngularFireList<any>;
items: Observable<any[]>;
constructor(db: AngularFireDatabase,public alertCtrl: AlertController,public loadingCtrl: LoadingController,
public navCtrl: NavController,public fire: AngularFireAuth) {
var newPostKey = db.database.ref().child('report').push().key;
this.reports = db.list(`report/${this.userId=fire.auth.currentUser.uid}/`);
console.log(this.userId=fire.auth.currentUser.uid)
}
formatDate (date): string{
const day = new Date().getDate();
const month = new Date().getMonth()+1;
const year = new Date().getFullYear();
return `${day}-${month}-${year}`
}
// dateaddread(dateadded){
// this.dateadded = this.formatDate(dateadded)
// }
Publish(name,title,dateadded){
if (name.trim().length === 0) {
console.log(this.name);
let alert = this.alertCtrl.create({
title: 'Error',
message: 'Please fill report blank ',
buttons: ['OK']
});
alert.present();
}else if (title.trim().length === 0){
let alert = this.alertCtrl.create({
title: 'Error',
message: 'Please fill title blank ',
buttons: ['OK']
});
alert.present();
}else {
this.reports.push({
name:name,
title:title,
Email:this.fire.auth.currentUser.email,
dateadded:this.formatDate(dateadded)
}).then(Newreport=>{
let alert = this.alertCtrl.create({
title: 'Successful',
message: 'Successfully posted',
buttons: [
{
text: 'Ok',
handler: () => {
let navTransition = alert.dismiss();
// start some async method
navTransition.then(() => {
this.navCtrl.pop().then(data => {
this.navCtrl.setRoot(FeedPage)
});
});
return false;
}
}]
});
alert.present()
})
}
}
any idea please with simple code ?
this.reports = db.list(`report/${this.userId=fire.auth.currentUser.uid}/`);
this.reports.push({
name:name,
title:title,
Email:this.fire.auth.currentUser.email,
dateadded:this.formatDate(dateadded)
})
and for displaying the data in HTML, you just need to modify your query to get only the data of logged in user
this.itemsRef = db.list(`report/` + fire.auth.currentUser.uid);
i am actually working on a mobile app in ionic v3 with angular5
The goal is to be able to take a picture or choose from existing ones and then upload it to the server. The first part is done, but i am struggling with the upload.
The api needs multipart/form-data which must consist of two requests. First with text part and second is the image.
Is there any solution for this?
This is what I have done for similar requirement
takePhoto() {
this.camera.getPicture({
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
sourceType: this.camera.PictureSourceType.CAMERA,
encodingType: this.camera.EncodingType.PNG,
saveToPhotoAlbum: true
}).then(imageData => {
this.myPhoto = imageData;
this.uploadPhoto(imageData);
}, error => {
this.functions.showAlert("Error", JSON.stringify(error));
});
}
selectPhoto(): void {
this.camera.getPicture({
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
destinationType: this.camera.DestinationType.FILE_URI,
quality: 100,
encodingType: this.camera.EncodingType.PNG,
}).then(imageData => {
this.myPhoto = imageData;
this.uploadPhoto(imageData);
}, error => {
this.functions.showAlert("Error", JSON.stringify(error));
});
}
private uploadPhoto(imageFileUri: any): void {
this.file.resolveLocalFilesystemUrl(imageFileUri)
.then(entry => (<FileEntry>entry).file(file => this.readFile(file)))
.catch(err => console.log(err));
}
private readFile(file: any) {
const reader = new FileReader();
reader.onloadend = () => {
const formData = new FormData();
const imgBlob = new Blob([reader.result], { type: file.type });
formData.append('evaluationID', this.currentEvaluation.evaluationId);
formData.append('standardID', this.currentEvaluation.id);
formData.append('score', this.currentEvaluation.score);
formData.append('comment', this.currentEvaluation.comment);
formData.append('file', imgBlob, file.name);
this.saveStandard(formData);
};
reader.readAsArrayBuffer(file);
}
And here is code for provider
saveStandard(receivedStandardInfo:any){
return new Promise((resolve, reject) => {
this.http.post(apiSaveStandard,receivedStandardInfo)
.subscribe(res => {
resolve(res);
}, (err) => {
console.log(err);
reject(err);
});
}).catch(error => { console.log('caught', error.message); });
}
I am working with this Angular 4 calendar:
https://mattlewis92.github.io/angular-calendar
I am trying to make a request to the api following the async method recommended in the github page, but it does not make the request unless if I use .toPromise(), but with that I do not know how to map
Here is my get of my calendar-component.ts:
params = new URLSearchParams();
options = new RequestOptions();
events: any[];
events$: Observable<Array<CalendarEvent<{ event: EventCalendar }>>>;
/***/
getEvents()
{
const getStart: any = {
month: startOfMonth,
week: startOfWeek,
day: startOfDay
}[this.view];
const getEnd: any = {
month: endOfMonth,
week: endOfWeek,
day: endOfDay
}[this.view];
this.params.set('beginning', format(getStart(this.viewDate), 'YYYY-MM-DD'))
this.params.set('end', format(getEnd(this.viewDate), 'YYYY-MM-DD'))
this.options.search = this.params
this.http
.request(ApiConfig.API_URL + 'calendar/RangeEvents', this.options)
.toPromise()
.then(() =>
{
res => res.json()
.map(({ results }: { results: EventCalendar[] }) =>
{
results.map((event: EventCalendar) =>
{
return {
title: event.title,
start: event.date,
color: colors.yellow,
allDay: true,
meta: {
event
}
}
})
})
})
}
I get the the request if I use this, but the html calendar does not get the events:
this.http
.get(ApiConfig.API_URL + 'calendar/RangeEvents', this.options)
.toPromise()
.then(response =>
{
this.events$ = response.json()
})
And I got this from Api:
{title: "Event 1", date: "2017-10-10T10:34:09"}
Html:
<mwl-demo-utils-calendar-header [(view)]="view"
[(viewDate)]="viewDate"
(viewDateChange)="fetchEvents()"
(viewChange)="fetchEvents()">
</mwl-demo-utils-calendar-header>
<ng-template #loading>
<div class="text-center">
<i class="fa fa-circle-o-notch fa-spin" style="font-size:40px"></i>
<br>
</div>
</ng-template>
<div *ngIf="events$ | async; else loading; let events">
<div [ngSwitch]="view">
<mwl-calendar-month-view *ngSwitchCase="'month'"
[viewDate]="viewDate"
[events]="events"
[activeDayIsOpen]="activeDayIsOpen"
(dayClicked)="dayClicked($event.day)"
(eventClicked)="eventClicked($event.event)">
</mwl-calendar-month-view>
<mwl-calendar-week-view *ngSwitchCase="'week'"
[viewDate]="viewDate"
[events]="events"
(eventClicked)="eventClicked($event.event)">
</mwl-calendar-week-view>
<mwl-calendar-day-view *ngSwitchCase="'day'"
[viewDate]="viewDate"
[events]="events"
(eventClicked)="eventClicked($event.event)">
</mwl-calendar-day-view>
</div>
</div>