I could register user(not admin), login, and store data in local.
But my program doesn't sync data to ROS2.
As far as I see document, maybe using Realm.Sync.addListener with admin.
I think admin user can access all object data. is wrong?
const addListener = (user) => new Promise((resolve, reject) => {
Realm.Sync.addListener('realm://usme-ros.usme.local:9080', user, '.*', 'change', (back) => {
console.log(back);
});
});
const registerUser = () => new Promise((resolve, reject) => {
Realm.Sync.User.register(URL, username, password, (err, res) => {
if (err) {
return reject(err);
}
console.log('finish register');
resolve();
})
});
const login = () => new Promise((resolve, reject) => {
Realm.Sync.User.login(URL, username, password, (err, user) => {
if (err) {
return reject(err);
}
resolve(user);
})
});
const registerVisit = (token) => new Promise((resolve, reject) => {
const visitSchema = {
name: 'Visit',
properties: {
id: 'int',
oneday_id: 'string',
arrival_date: 'string',
departure_date: 'string',
latitude: 'double',
longitude: 'double',
is_hidden: 'bool',
}
};
Realm.openAsync({ schema: [visitSchema] }, (err, realm) => {
if (err) {
return reject(err);
}
realm.write(() => {
realm.create('Visit', {
id: 1,
oneday_id: "ABCD-EFGH-IJKL-MNOP-QRST",
arrival_date: "2017-11-05 11:11:11",
departure_date: "2017-11-05 22:22:22",
latitude: 23.1234567,
longitude: 12.34567,
is_hidden: false,
});
});
resolve();
});
});
login()
.then((user) => addListener(user)
.then(() => registerVisit())
.catch(err => console.log(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 function that create tasks and writing it in firebase real time database.
export const createNewTask = (task) => new Promise(async (resolve, reject) => {
try {
await database().ref('tasks').child(auth().currentUser.uid).child(task.taskCreationDate.toString()).set(task);
resolve();
} catch (e) {
reject(e);
}
});
And it's working good :
Now, I have a socond functions that should read that tasks.
export const fetchTasks = () => (dispatch) => new Promise(async (resolve, reject) => {
try {
const snapshot = await database().ref('tasks').child(auth().currentUser.uid).once('value');
if (snapshot.exists) {
const tasks = snapshot.val();
dispatch({
type: FETCH_TASKS,
payload: tasks,
});
resolve(tasks);
} else {
resolve(snapshot);
}
} catch (e) {
reject(e);
}
});
And here is the problem:
When I'm using useSelector in my home screen const tasks = useSelector(state => state.GeneralReducer.taskList);
The tasks list is undefiend.
When I used mock data with same objects , it's work fine.
How can I get a list of task?
Ok , fixed it by adding :
Object.keys(data).map(key => ({...data[key], id: key}));
to the function fetchTasks.
export const fetchTasks = () => (dispatch) => new Promise(async (resolve, reject) => {
try {
const snapshot = await database().ref('tasks').child(auth().currentUser.uid).once('value');
if (snapshot.exists) {
const data = snapshot.val();
const tasks = Object.keys(data).map(key => ({...data[key], id: key}));
dispatch({
type: FETCH_TASKS,
payload: tasks,
});
resolve(tasks);
} else {
resolve(snapshot);
}
} catch (e) {
reject(e);
}
});
I'm trying to show some message through ion-alert after getting data by getTask(taskId).
But seems it shows alert dialogue before data returned, so this.item in message shows undefined.
How can I make sure data returned before showing alert dialogue?
list.page.ts
items: Array<any>;
item: any;
constructor(
public loadingCtrl: LoadingController,
private authService: AuthService,
private router: Router,
private route: ActivatedRoute,
private firebaseService: FirebaseService,
private alertCtrl: AlertController,
) { }
async delete(clickedItem: any) {
let itemId = clickedItem.payload.doc.id;
this.firebaseService.getTask(itemId)
.then(data => {
this.item = data;
}, err => {
console.log(err);
});
const alert = await this.alertCtrl.create({
header: 'Confirm',
// this.item is undefined here
message: 'Do you want to delete ' + this.item.title + '?',
buttons: [
{
text: 'No',
role: 'cancel',
cssClass: 'secondary',
handler: () => {}
},
{
text: 'Yes',
handler: () => {
this.firebaseService.deleteTask(itemId)
.then(
res => {
this.router.navigate(["/list"]);
},
err => console.log(err)
)
}
}
]
});
await alert.present();
}
firebase.service.ts
getTask(taskId){
return new Promise<any>((resolve, reject) => {
this.afAuth.user.subscribe(currentUser => {
if(currentUser){
this.snapshotChangesSubscription = this.afs.doc<any>('people/' + currentUser.uid + '/tasks/' + taskId).valueChanges()
.subscribe(snapshots => {
resolve(snapshots);
}, err => {
reject(err)
})
}
})
});
}
Try it:
async delete(clickedItem: any) {
let itemId = await clickedItem.payload.doc.id;
await this.firebaseService.getTask(itemId)
.then(data => {
this.item = data;
}, err => {
console.log(err);
});
const alert = await this.alertCtrl.create({
header: 'Confirm',
// this.item is undefined here
message: 'Do you want to delete ' + this.item.title + '?',
buttons: [
{
text: 'No',
role: 'cancel',
cssClass: 'secondary',
handler: () => {}
},
{
text: 'Yes',
handler: () => {
this.firebaseService.deleteTask(itemId)
.then(
res => {
this.router.navigate(["/list"]);
},
err => console.log(err)
)
}
}
]
});
await alert.present();
}
Or You can also try It
async delete(clickedItem: any) {
let itemId = await clickedItem.payload.doc.id;
this.firebaseService.getTask(itemId)
.then(async data => {
this.item = data;
const alert = await this.alertCtrl.create({
header: 'Confirm',
// this.item is undefined here
message: 'Do you want to delete ' + this.item.title + '?',
buttons: [
{
text: 'No',
role: 'cancel',
cssClass: 'secondary',
handler: () => {}
},
{
text: 'Yes',
handler: () => {
this.firebaseService.deleteTask(itemId)
.then(
res => {
this.router.navigate(["/list"]);
},
err => console.log(err)
)
}
}
]
});
await alert.present();
}, err => {
console.log(err);
});
}
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 have a getProgrammeWrapper method that returns a promise. However in .then method i have few other promises that i will like to execute before returning the programmeWrapper[]
This is service.ts
I am calling the service in ngOnInit
this.service.getProgrammesByWrapper().then(((res) => {
this.programmes = res;
this.result.updateInfo("Sorting classes...")
this.programmes =this.programmes.sort((a,b) => {
return b.programme.click - a.programme.click;
});
this.result.updateSuccess(true);
}));
I hope i have explained the issue clearly. I have tried using await, but it doesn't work as expected.
getProgrammeWrapper()
getProgrammesByWrapper(): Promise<ProgrammeWrapper[]> {
var current = this;
var programmesDTO = new Array<ProgrammeWrapper>();
var table = this.client.getTable("programme");
return new Promise((resolve, reject) => {
table.read()
.then(function (modules) {
modules.forEach(element => {
var newProgDTO = new ProgrammeWrapper(element);
current.getLessonsByProgrammeId(element.id).then(lessons => newProgDTO.lesson = lessons).catch(err => console.log(err));
current.getUser(element.tutorId).then(user => newProgDTO.tutor = user).catch(err => console.log(err));
programmesDTO.push(newProgDTO)
});
resolve(programmesDTO)
}, function (error) { reject(error) });
});
}
I'm not sure it would work, could have bugs too. Try this:
getProgrammesByWrapper(): Promise<ProgrammeWrapper[]> {
var current = this;
var programmesDTO = new Array<ProgrammeWrapper>();
var table = this.client.getTable("programme");
return new Promise((resolve, reject) => {
table.read()
.then(function (modules) {
let promises = new Array<Promise<any>>();
modules.forEach(element => {
var newProgDTO = new ProgrammeWrapper(element);
let promise = current.getLessonsByProgrammeId(element.id)
.then(lessons => newProgDTO.lesson = lessons)
.catch(err => console.log(err));
promises.push(promise);
promise = current.getUser(element.tutorId)
.then(user => newProgDTO.tutor = user)
.catch(err => console.log(err));
promises.push(promise);
programmesDTO.push(newProgDTO)
});
// Wait for all promises to be ready before resolving
Promise.all(promises).then(function() {
resolve(programmesDTO);
});
}, function (error) { reject(error); });
});
}