Ionic2/Angular2 Http is not working - android

I am new to Ionic framework and Angular2. I am unable to send post request to the server. I can't figure out what thing I am missing.
My App code:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import {Camera} from 'ionic-native';
import { Http, Headers, HTTP_PROVIDERS } from 'angular2/http';
import 'rxjs/Rx';
#Component({
selector: 'page-upload',
templateUrl: 'upload.html'
})
export class UploadPage {
public base64Image: string;
array = Array<any>;
loading: boolean;
constructor(public navCtrl: NavController,public http: Http) {
}
takePicture(){
Camera.getPicture({
destinationType: Camera.DestinationType.DATA_URL,
targetWidth: 1000,
targetHeight: 1000
}).then((imageData) => {
// imageData is a base64 encoded string
this.base64Image = "data:image/jpeg;base64," + imageData;
}, (err) => {
console.log(err);
});
}
accessGallery(){
Camera.getPicture({
sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
destinationType: Camera.DestinationType.DATA_URL
}).then((imageData) => {
this.base64Image = 'data:image/jpeg;base64,'+imageData;
}, (err) => {
console.log(err);
});
}
makePostRequest() {
this.http.get('https://public-api.wordpress.com/rest/v1.1/freshly-pressed/').subscribe(data => {
});
}
}
When I compile the app for android I get the following error:
L16: constructor(public navCtrl: NavController,public http: Http) {
Cannot find name 'Http'.

I checked one of my Ionic 2 projects and your imports should be
import {Http, Headers, RequestOptions, Response} from '#angular/http';
check your package.json and fix your project dependencies. You could use this project for references
https://github.com/driftyco/ionic-conference-app/blob/master/package.json

Related

Uploading Image from android file system to Firebase Storage

I am currently creating a page that allows users to take pictures of both their identity card and selfie of themselves, however, i am not able to get the files from the file system to upload it using submitpicture().
Here is my typescript code:
import { Component, OnInit } from '#angular/core';
import { File } from '#ionic-native/file/ngx';
import { Camera, CameraOptions } from '#ionic-native/camera/ngx';
import * as firebase from 'firebase';
import { EmailComposer } from '#ionic-native/email-composer/ngx';
import { ModalController } from '#ionic/angular';
#Component({
selector: 'app-verifyidentity',
templateUrl: './verifyidentity.page.html',
styleUrls: ['./verifyidentity.page.scss'],
})
export class VerifyidentityPage implements OnInit {
constructor(public camera: Camera, public file: File, private modalController: ModalController, public emailComposer: EmailComposer) { }
nric: any;
selfie: any;
nricimageData: any;
selfieimageData: any;
ngOnInit() {
}
takenric() {
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
saveToPhotoAlbum: true,
cameraDirection: 1
}
this.camera.getPicture().then((imageData) => {
this.nricimageData = imageData
let filename = imageData.substring(imageData.lastIndexOf('/') + 1);
let path = imageData.substring(0, imageData.lastIndexOf('/') + 1);
this.file.readAsDataURL(path,filename).then((base64data) => {
this.nric = base64data;
firebase.storage().ref().child("test").put(imageData).then(snapshot => {
console.log('Uploaded image ');
});
})
});
}
takeselfie() {
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
saveToPhotoAlbum: true,
cameraDirection: 1
}
this.camera.getPicture().then((imageData) => {
this.selfieimageData = imageData
let filename = imageData.substring(imageData.lastIndexOf('/') + 1);
let path = imageData.substring(0, imageData.lastIndexOf('/') + 1);
this.file.readAsDataURL(path,filename).then((base64data) => {
this.selfie = base64data;
firebase.storage().ref().child("test").put(imageData).then(snapshot => {
console.log('Uploaded image ');
});
})
});
}
submitpicture() {
firebase.storage().ref().child("nric").put(this.nric); // this does not work!
}
I was wondering if it is possible to get the image from the android system with the file path and store it in a variable before uploading to firebase storage with submitpicture().
So sorry for any inconvenience caused and thank you.
Best regards,
Dan

how to launch camera in an ionic app

I have created the basic ionic app which can launch camera. I installed all the required plugins and also i have used the right version of cordova . I am not getting any errors and also able to create apk for that . When using in apk in the android mobile, camera is not getting launched.
this is the home.html code adding camera module
<button ion-button (click)="takePhoto()">camera</button>
<p align="center"><img src="{{ myphoto }}"></p>
this is the home.ts file
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Camera, CameraOptions } from '#ionic-native/camera';
import { Database } from '../../providers/database/database';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
tabBarElement: any;
splash = true;
myphoto:any;
public hasTrees : boolean = false;
public trees : any;
constructor(public navCtrl: NavController, private camera:Camera,
public DB : Database) {
this.tabBarElement = document.querySelector('.tabbar');
}
takePhoto(){
const options: CameraOptions = {
quality: 70,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64:
this.myphoto = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
}
ionViewDidLoad() {
this.tabBarElement.style.display = 'none';
setTimeout(() => {
this.splash = false;
this.tabBarElement.style.display = 'flex';
}, 4000);
}
ionViewWillEnter()
{
this.displayTrees();
}
displayTrees()
{
this.DB.retrieveTrees().then((data)=>
{
let existingData = Object.keys(data).length;
if(existingData !== 0)
{
this.hasTrees = true;
this.trees = data;
}
else
{
console.log("we get nada!");
}
});
}
addSpecies()
{
this.navCtrl.push('Add');
}
viewSpecies(param)
{
this.navCtrl.push('Add', param);
}
}

ionic2 Streaming Media is not working

I'm using the streaming media plugin in my ionic2 application.
this is my code:
let option:StreamingAudioOptions = {
successCallback: () => { console.log('Audio played') },
errorCallback: (e) => { console.log(JSON.stringify(e,null,2)) }
}
this.streamingMedia.playAudio('http://sounddible.com/grab.php?id=2196&type=mp3',option);
the errorCallback return "Class not found"
Any help for explain the reason of this log
Thanks.
try below code :
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { StreamingMedia, StreamingAudioOptions } from '#ionic-native/streaming-media';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController,private streamingMedia: StreamingMedia) {}
startAudio(){
let options: StreamingAudioOptions = {
successCallback: () => { console.log('Video played') },
errorCallback: (e) => { console.log(JSON.stringify(e,null,2)) },
initFullscreen:false,
};
this.streamingMedia.playAudio('YOUR_URL', options);
}

Photo not displayed when selected from photo library in Ionic 2

I am using Camera plugin in Ionic 2 for uploading photos. I am running the app on an Android device. The Carema capture is displayed in the app but when selected from Gallery the photo is not displayed.
The following methods are used for Camera and Gallary:
private openCamera(){
var options: CameraOptions = {
sourceType: this.camera.PictureSourceType.CAMERA,
destinationType: this.camera.DestinationType.DATA_URL,
allowEdit: true,
saveToPhotoAlbum: true
};
this.camera.getPicture(options).then((imageData) => {
this.cameraData = 'data:image/jpeg;base64,' + imageData;
this.photoTaken = true;
this.photoSelected = false;
let base64Image = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
}
private selectFromGallery() {
var options = {
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
destinationType: this.camera.DestinationType.FILE_URI
};
this.camera.getPicture(options).then((imageData) => {
this.cameraUrl = imageData;
this.photoSelected = true;
this.photoTaken = false;
}, (err) => {
// Handle error
});
}
Following is the code to display in HTML page:
<img [src]="cameraData" *ngIf="photoTaken">
<img [src]="cameraUrl" *ngIf="photoSelected">
You need to use a file plugin to obtain local filesystem url when you select from library.
To install:
$ ionic cordova plugin add cordova-plugin-file
$ npm install --save #ionic-native/file
Import:
import { File } from '#ionic-native/file';
and in your code:
constructor( private file: File, .... ) {}
.....
const options: CameraOptions = {
destinationType: this.camera.DestinationType.FILE_URI,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
}
this.camera.getPicture(options).then((imageURI) => {
this.file.resolveLocalFilesystemUrl(imageURI).then(fileEntry => {
this.cameraUrl = fileEntry.nativeURL;
this.photoSelected = true;
this.photoTaken = false;
});
}, (err) => {
// Handle error
});
EDIT
You might need to sanitize the value for img src:
<img *ngIf="cameraUrl" [src]="sanitizeUrl(cameraUrl)" />
The function:
import { DomSanitizer } from '#angular/platform-browser';
....
constructor( private sanitizer: DomSanitizer, .... ) {}
....
sanitizeUrl(url) {
return this.sanitizer.bypassSecurityTrustUrl(url);
}

Open a file within the app folder with fileOpener Ionic2

this is my code :
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { FileOpener } from 'ionic-native';
#Component({
selector: 'page-installHelper',
templateUrl: 'installHelper.html'
})
export class InstallHelper {
constructor(public navCtrl: NavController) {
FileOpener.open('assets/app.apk', 'application/vnd.android.package-archive').then(
function(){
console.log("success");
}, function(err){
console.log("status : "+err.status);
console.log("error : "+err.message);
});
}
}
but I can't access the file app.apk which is in assets/app.apk
and I get the error :
Status : 9
Error : File Not Found
is it even possible to access a file within the app folders ?
Well I did it by making the app get downloaded from a server to a local folder I created in the phone and install it immediately/automatically,
Here is the code in case someone else needed it one day :
import { Component } from '#angular/core';
import { Platform, LoadingController } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { FileOpener } from 'ionic-native';
import { File } from 'ionic-native';
import { Transfer } from 'ionic-native';
import { HomePage } from '../pages/home/home';
declare var cordova: any;
#Component({
template: `<ion-nav [root]="rootPage"></ion-nav>`
})
export class MyApp {
rootPage = HomePage;
constructor(platform: Platform, public loadingCtrl: LoadingController) {
let me = this;
platform.ready().then(() => {
let loading = me.loadingCtrl.create({
content: 'Preparing The App ...'
});
loading.present();
File.createDir(cordova.file.externalDataDirectory, "appFolder", true).then(function(link){
const fileTransfer = new Transfer();
let url = 'http://yourserverhere.com/app.apk';
fileTransfer.download(url, cordova.file.externalDataDirectory +"appFolder/app.apk").then((entry) => {
loading.dismiss();
FileOpener.open(entry.toURL(), "application/vnd.android.package-archive").then(
function(){
console.log("success");
},function(err){
console.log("status : "+err.status);
console.log("error : "+err.message);
});
}, (error) => {
console.log(error);
});
},function(error){
console.log(error);
});
StatusBar.styleDefault();
Splashscreen.hide();
});
}
}
Any explanation just ask me.
Well since you want the user to download the .apk file, you could use (in your html)
<a href="assets/app.apk" download>Download apk</a>
But the user will have to manually open his downloads (or tap the popup) to install your app.
I do not know if there is a plugin which is capable of installing these apk files. (Googling for ionic 2 install external apk didn't return any results).

Categories

Resources