One of the features on my application involves a camera page that is accessed by other pages. This camera page includes functions related to the camera preview (camera.ts):
// camera.ts
import { Component, OnInit } from '@angular/core';
import {CameraPreview, CameraPreviewOptions, CameraPreviewPictureOptions} from '@ionic-native/camera-preview/ngx';
import {Platform} from '@ionic/angular';
import {GlobalDataService} from '../../../services/global-data.service';
import {Router} from '@angular/router';
@Component({
selector: 'app-camera',
templateUrl: './camera.page.html',
styleUrls: ['./camera.page.scss'],
})
export class CameraPage implements OnInit {
cameraPreviewOpts: CameraPreviewOptions = {
x: 0,
y: 0,
width: window.screen.width,
height: window.screen.height,
camera: 'rear',
tapPhoto: true,
previewDrag: true,
toBack: true,
alpha: 1
};
// picture options
pictureOpts: CameraPreviewPictureOptions = {
width: 1280,
height: 1280,
quality: 85
};
constructor(private router: Router, private cameraPreview:
CameraPreview, public platform: Platform, private globalDataService:
GlobalDataService) {
// solve the problem - "plugin not installed".
platform.ready().then(() => {
this.openCamera();
});
}
selectedImage: any;
ngOnInit() {
}
openCamera() {
console.log('open camera');
// start camera
this.cameraPreview.startCamera(this.cameraPreviewOpts).then(
(res) => {
console.log('cameraPreview.start');
console.log(res);
},
(err) => {
console.log('cameraPreview.start fails');
console.log(err);
});
}
takePicture() {
console.log('take picture');
// take a picture
this.cameraPreview.takePicture(this.pictureOpts).then((imageData) => {
this.selectedImage = 'data:image/jpeg;base64,' + imageData;
console.log('take picture');
this.globalDataService.changePictureTaken(this.selectedImage);
// replace with router to the back page
// this.router.
}, (err) => {
console.log(err);
this.selectedImage = 'assets/img/test.jpg';
});
}
cerrarCamara() {
this.cameraPreview.stopCamera();
}
}
Let's consider an example with 3 pages:
1 - Camera page
2 - Page A
3 - Page B
Page A loads the camera through the routing module:
this.router.navigateByUrl('/camera');
Similarly, page B does the same (not simultaneously):
this.router.navigateByUrl('/camera');
In the camera.ts code, after taking a picture (takePicture() method), I aim to return to the page from which this page was called, essentially mimicking the action of pressing the back button on a phone.
For instance, if page A navigates to the camera, takes a picture, I would like to navigate back to A. Similarly, if page B goes to camera, takes a picture, and then routes back to B.
Essentially, I do not want to use router.navigateByUrl every time, as I do not always want to navigate to the same page, but rather to the previous page.
Is there a way to achieve this in TypeScript?