I'm trying to upload an get photo in my Ionic 2 app. I succeeded to run the camera and save the photo in Firebase but not to get and display it on my app. I'm not sure i'm doing it right, the save in Firebase.
I put here my code.
add-note.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Camera } from 'ionic-native';
import {NotesData} from "../../providers/notes-data";
/*
Generated class for the AddNote page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
#Component({
selector: 'page-add-note',
templateUrl: 'add-note.html'
})
export class AddNote {
public notePicture: any;
constructor(public navCtrl: NavController,public notesData:NotesData) {}
ionViewDidLoad() {
}
addNote() {
this.notesData.addPhoto(this.notePicture);
this.navCtrl.pop();
}
takePicture(){
Camera.getPicture({
quality : 95,
destinationType : Camera.DestinationType.DATA_URL,
sourceType : Camera.PictureSourceType.CAMERA,
allowEdit : true,
encodingType: Camera.EncodingType.PNG,
targetWidth: 500,
targetHeight: 500,
saveToPhotoAlbum: true
}).then(imageData => {
this.notePicture = imageData;
}, error => {
console.log("ERROR -> " + JSON.stringify(error));
});
}
}
note-data.ts //provider for notes to upload the photo to firebase
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
import firebase from 'firebase'
/*
Generated class for the NotesData provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
#Injectable()
export class NotesData {
//user data
public currentUser: any;
public profilePictureRef: any;
//notedata
public notesList: any;
//firebase data
public photoRef:any;
constructor() {
this.currentUser = firebase.auth().currentUser.uid;
this.fireRef=firebase.database().ref();
this.photoRef=firebase.database().ref('users/'+this.currentUser+'/photos');
this.notesList =
}
addPhoto(notePicture:any){
this.photoRef.push({id:"data:image/jpeg;base64,"+notePicture});
}
}
my firebase structure photo
You want to use Firebase Storage and store URLs in your Firebase. You're going to cost yourself a lot of extra money and headaches by storing your image data in the realtime database.
The new SDKs have great APIs for uploading images that can be publicly accessed.
Don't save the whole url, just save short path. As you can find at my blog post about uploading, and getting data from firebase storage, it's just 2 lines of code to get actual url with permissions.
this.storageRef = firebase.storage().ref().child('images/image.png');
this.storageRef.getDownloadURL().then(url =>
console.log(url)
);
you can use angular-firebase npm package it is simple and easy to use
npm install angular-firebase
and you can simply upload the captured base 64 image
with this code
this.firebase.uploadString(encodedFile,'images/1.jpg','base64',
(v)=>{
console.log('Upload progress :'v + '% uploaded');
// event detect the data uploaded used to monitor the persentage of the download process
// this will return 'Upload progress : 24% uploaded'
// for example
}).then((url)=>{
console.log(url);
//the URL of uploaded file or image
});
Related
The ionViewDidLoad function seem to get called twice, which is causing multiple views being created of AddressPage. I have debugged this and it looks like whenever data is updated the new instance of view gets created. This behaviour seems to happen only when I use fireabse to save the address. If I comment out the code to save the address new view is not created and app navigates to previous screen.
Any way to avoid this?
I have tried ViewCotnroller.dismiss() and NavController.pop() inside saveAddress method but non seem to avoid creation of new view.
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any = HomePage;
constructor(platform: Platform, statusBar: StatusBar) {
platform.ready().then(() => {
statusBar.styleDefault();
statusBar.backgroundColorByHexString('#1572b5');
});
}
}
Home Page
import {NavController } from 'ionic-angular';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController, public firebaseProvider:
FirebaseProvider) {
}
//navigate to different view
navigate(){
this.navCtrl.push(AddressPage, {address:newAddress});
}
}
Address Page
import {NavController } from 'ionic-angular';
#Component({
selector: 'page-address',
templateUrl: 'address.html'
})
export class AddressPage {
constructor(public navCtrl: NavController, public firebaseProvider:
FirebaseProvider, private navParams: NavParams) {
this.addressKey = this.navParams.get('key');
}
ionViewDidEnter(){
//load some data from server
}
saveAddress(){
//save data to server
this.firebaseProvider.saveAddress(newAddress);
//move back
this.navCtrl.pop();
}
}
Firebase provider that uses AngularFireDatabase
import { Injectable } from '#angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
#Injectable()
export class FirebaseProvider {
constructor(public afd: AngularFireDatabase) { }
saveAddress(address) {
this.afd.list('/addresses').push(address);
}
updateAddress(key,dataToUpdate){
return this.afd.list('addresses').update(key,dataToUpdate);
}
}
I have also tried this but it has the same issue.
this.firebaseProvider.saveAddress(newAddress).then(result => {
// loadingSpinner.dismiss();
this.navCtrl.pop();
});
this.firebaseProvider.updateAddress(this.addressKey, updateItems)
.then(() => {
// loadingSpinner.dismiss();
this.navCtrl.pop()
});
The HTML of save button
<button type="button" ion-button full color="primary-blue" (click)='saveAddress()'>Save</button>
Looks like unsubscribing to the subscribers fixes the issue. The HomePage view had subscribers which were not unsubscribed. I added the Observable Subscriptions into the array and unsubscribed as per code below.
ionViewWillLeave(){
this.subscriptions.forEach(item=>{
item.unsubscribe();
});
}
the push method returs a promise with the result of the action. I would change the save method like this:
saveAddress(address) {
return this.afd.list('/addresses').push(address);
}
Then in the controller I’d change it in this way:
saveAddress(){
//save data to serve
this.firebaseProvider.saveAddress(newAddress).then(result => {
//do yours validations
this.navCtrl.pop();
});
}
With thos you tide up the navigation of the page to the result of the Firebase execution. Give it a try to this approach and let me know if it didn’t work, anyway I would use oninit to load data only once as I guess you wanna do it rather than ionViewDidEnter.
I am trying to execute file transfer from a Flask server to an Ionic3 application. Basically, what I want to do is send a .vcf file from the server to the application to them be read and displayed in the application. The application does not need to store the file in any form of persistent memory.
When I try to do this, I get a ton of error. The one I am encountering right now is:
Encountered undefined provider! Usually this means you have circular dependencies (might be caused by using 'barrel' index.ts files.
I tried making a whole separate provider file for file-transfer but that just gave me other errors. Currently, my .ts file that is throwing the error is as follows:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Transfer, TransferObject } from '#ionic-native/file-transfer';
import { File } from '#ionic-native/file';
#IonicPage()
#Component({
selector: 'page-quiz',
templateUrl: 'quiz.html',
providers: [Transfer, TransferObject, File]
})
export class QuizPage {
storageDirectory: string = '';
constructor(public navCtrl: NavController, public navParams: NavParams,
private transfer: FileTransfer, private file: File) {
this.vCardDownload("b734cdc8-8ec1-4fde-b918-b6062b5099df");
}
ionViewDidLoad() {
console.log('ionViewDidLoad QuizPage');
}
vCardDownload(uuid) {
const fileTransfer: TransferObject = this.transfer.create();
const vCardLocation = 'http://xxxxxxx.xxx.edu:5000/get_question_vCard?uuid=' + uuid;
fileTransfer.download(vCardLocation, this.file.applicationDirectory + uuid).then((entry) => {
console.log("file was downloaded", entry.toURL());
alertSuccess.present();
}, (error) => {
console.log("ERROR file was not downloaded");
});
}
}
Where am I going wrong here and how can I achieve file transfer? I think I am on the right track to getting it working -- I am pretty new to typescript and mobile development so I apologize in advance for any mistakes. Essentially I want to "capture the file within the application."
It turns out I had two errors. First, my import statements were wrong. Second, I didn't add certain imports to the providers listing in my app.module.ts file.
Here are my providers in app.module.ts:
import { File } from '#ionic-native/file';
import { FileTransfer } from '#ionic-native/file-transfer';
... declarations, imports, etc. ...
providers: [
StatusBar,
SplashScreen,
File,
FileTransfer,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
Here is the sample code I used to download the .vcf file.
import { FileTransfer, FileTransferObject } from '#ionic-native/file-transfer';
import { File } from '#ionic-native/file';
...
constructor(public navCtrl: NavController, public navParams: NavParams,
private transfer: FileTransfer, private file: File) {
this.vCardDownload("XXXXXX-XXXXX-XXXX-XXXX");
}
...
vCardDownload(uuid) {
console.log("Trying to download vCard!");
const fileTransfer: FileTransferObject = this.transfer.create();
const vCardLocation = 'http://XXXXXX.XXX.edu:5000/get_question_vCard?uuid=' + uuid;
fileTransfer.download(vCardLocation, this.file.dataDirectory + 'file.vcf').then((entry) => {
console.log('download complete: ' + entry.toURL());
}, (error) => {
console.error(error);
});
}
Note that so far this only works for me on a mobile device.
In an Ionic project i am using the code below to load a document collection from Firestore with the AngularFirestore wrappers.
Now that the content starts loading when the view was initialized i'm experiencing a delay by about 4-8 seconds until the firestore fetched data renders in my list-view, which is very very bad for the overall userexperience.
with the code below i'm able to show a loading spinner when the content starts loading bit i need it to stop showing the loader.
I have no clue how to trigger that event? Any help would be appreciated
thank you very much
import { City } from './../../model/City';
import { Component, AfterViewInit } from '#angular/core';
import { NavController, IonicPage, LoadingController } from 'ionic-angular';
import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
#IonicPage()
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage implements AfterViewInit {
citiesRef: AngularFirestoreCollection<City>
cities: Observable<City[]>;
loading = this.loadingCtrl.create({
content: 'Loading Regions...'
});
constructor(private loadingCtrl: LoadingController, private afs: AngularFirestore, public navCtrl: NavController) {
}
ngAfterViewInit(){
this.loading.present().then(()=>{
this.citiesRef = this.afs.collection<City>('regions', ref => ref.orderBy('name'));
this.cities = this.citiesRef.valueChanges();
})
}
}
Well, what I did was I subscribe to the this.cities. It worked in my case. The idea is it will fire loading.dismiss() once it is able to subscribe. Hope that helps
let loading = this.loadingCtrl.create({
content: 'Please wait...'
});
loading.present();
this.citiesRef=this.afs.collection('cities');
this.cities=this.citiesRef.valueChanges();
this.cities.subscribe(_=>{
loading.dismiss();
})
Followed the content of the url to implement dynamic menu items using JSON file stored under /assets/data. The menu is working fine with stored JSON file. Now I need to dynamically retrieve the JSON of same format in real time from a Salesforce API and display its content.
Can someone please suggest what changes I need to make here? should the json path in getMainMenu() method be replaced with the actual Saleforce API?
Below is the data-service.ts
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the DataServiceProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
#Injectable()
export class DataServiceProvider {
constructor(public http: Http) {
console.log('Hello DataServiceProvider Provider');
}
getMainMenu(){
return this.http.get('assets/data/mainmenu.json')
.map((response:Response)=>response.json().Categories);
}
}
and app.component.ts
import { Component, ViewChild } from '#angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { DataServiceProvider } from '../providers/data-service/data-service'
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage: any = HomePage;
pages: any[]; //Array<{title: string, component: any}>;
mainmenu: any[];
constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen, public dataService: DataServiceProvider) {
this.initializeApp();
this.dataService.getMainMenu().subscribe((Response)=>{
this.mainmenu = Response;
console.log(this.mainmenu);
});
// used for an example of ngFor and navigation
this.pages = [
{ title: 'Home', component: HomePage },
{ title: 'List', component: ListPage }
];
}
initializeApp() {
this.platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
openPage(page) {
// Reset the content nav to have just this page
// we wouldn't want the back button to show in this scenario
this.nav.setRoot(page.component);
}
toggleSection(i) {
this.mainmenu[i].open = !this.mainmenu[i].open;
};
toggleItem(i,j) {
this.mainmenu[i].SubCategories[j].open = !this.mainmenu[i].SubCategories[j].open;
};
}
It looks like you will need to update the url in the getMainMenu method to that of your api. There might be some other changes you will need to make, such as adding authentication headers, but if the data coming from the api is the same as whats stored in the assets folder, your component shouldn't care "where" the data comes from.
What I am trying to do is when the splash screen is loading, a http request is made to the server to pull some information and pass the response to another page.
Below is the code I am working with.
import { Component } from '#angular/core';
import { Platform, LoadingController } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { CacheService } from "ionic-cache/ionic-cache";
import { Apis } from './apis';
import { StayPage} from '../pages/stay/stay';
#Component({
templateUrl: 'app.html',
providers: [Apis]
})
export class MyApp {
rootPage = StayPage;
constructor(platform: Platform, cache: CacheService, public loadingCtrl: LoadingController, public Apis: Apis ) {
cache.setDefaultTTL(60 * 60);
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
this.Apis.types().subscribe( response => {
response.results;
StatusBar.styleDefault();
Splashscreen.hide();
}, err => {
this.Apis.error( err );
});
});
}
}
When I run the above code, the splash screen is stuck on loading and doesn't move to another page.
You need to make HTTP request in constructor or ngOnInit of StayPage.
export class StayPage implements OnInit {
...
constructor(public navCtrl: NavController,
public navParams: NavParams
public http: Http) { }
ngOnInit(){
this.http.get(apiUrl)
.subscribe(
responseSuccess => ...
responseError => ...
}
}
}