Navigating back to the previous page: Implementing the Router Module in Ionic 4 with Angular

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?

Answer №1

If you need to go back to the previous page, you can utilize the location.back() method.

import {Component} from '@angular/core';
import {Location} from '@angular/common';

@Component({
  selector: 'app-camera',
  templateUrl: './camera.page.html',
  styleUrls: ['./camera.page.scss'],
})
class CameraPage {

  constructor(private location: Location) {}

  onBackClicked() {
    this.location.back();
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Challenges with importing VideoJs VR in Angular

Apologies for what may seem like a silly question, but I'm relatively new to Angular and I'm encountering some issues with VideoJs VR. Everything works fine with VideoJs, but when attempting to use VR for a 360-degree video, I'm seeing the f ...

Is there a way to convert a File into a byte array and then save it in a database using Angular and ASP.Net Core?

Hey everyone, I'm fairly new to working with Angular and I've hit a roadblock when trying to implement file-upload functionality in my Angular application. The technologies I am using include Angular, ASP.Net Core, and Sqlserver. I am tasked wi ...

When you use Array.push, it creates a copy that duplicates all nested elements,

Situation Currently, I am developing a web application using Typescript/Angular2 RC1. In my project, I have two classes - Class1 and Class2. Class1 is an Angular2 service with a variable myVar = [obj1, obj2, obj3]. On the other hand, Class2 is an Angular2 ...

There was an error when trying to read the file '.angular-cli.json'. Please double-check to ensure that the file contains valid JSON format. The error message indicates an unexpected

After installing npm install ng-file-upload, I added the ng-file-upload package to my project. Unfortunately, I am encountering errors in my project now. D:\web\ng4fbbootstrap\node_modules\@angular\cli\models\config&bsol ...

Establish a route nickname for files outside the project directory

I'm currently tackling a project that is divided into multiple angular projects. Within these projects, there are some services that are shared. Is there a way for me to incorporate these services into my project without encountering errors? /root / ...

Is Jasmine brushing off TypeScript test files?

I'm diving into my first project with Jasmine, and despite following a tutorial, I'm encountering some hurdles right from the start. After installing jasmine-node, typings, and typescript, I executed: typings install dt~jasmine --save-dev --glo ...

Changing an element within an item stored in Ionic Storage

Hello, I am currently attempting to update a specific part of an object stored in Ionic storage. The current data in the Storage looks like this: key : object value : {a: "1", b: "2", c: "3"} To modify one of the values to 10, I created the following fu ...

Problems arising from the layout of the PrimeNG DataView component when used alongside Prime

I've been working with a PrimeNG DataView component that requires the use of PrimeFlex's flex grid CSS classes to set up the grid structure. One of their examples includes the following instructions: When in grid mode, the ng-template element ...

Leveraging Express Mergeparams in TypeScript

I've run into an issue while working on my small project in Typescript. The problem arises when I attempt to nest my router, as Typescript doesn't seem to acknowledge the parent's parameter. Within the "child" file, I have the following cod ...

Bootstrap Modal - Preselected Dropdown Option

When using Bootstrap Modal, I am encountering an issue where the default option is not being displayed correctly. Instead of "Please Select" appearing as the default choice in the drop-down, it is showing up as "A" by default. Below is the HTML code snip ...

Unleash the full power of Angular Components by enhancing them with injected

I am facing a challenge with handling the destruction event of an Angular component in my external module that provides a decorating function. I've run into issues trying to override the ngOnDestroy() method when it includes references to injected ser ...

The observable of type 'any' does not contain the property 'subscribe'

When trying to extract data from googleTagmanger, I encountered an error stating that "Property 'subscribe' does not exist on type 'Observable'". Below is the code snippet I used: this.translate.get('newtest.testsimulation'). ...

Can an Angular 2 module export an interface?

While attempting to export an interface in a NgModule-declaration, I encountered an error message in my editor (Visual Studio Code) stating: [ts] 'MyInterface' only refers to a type, but is being used as a value here. Below is the code snippet c ...

Command to update a document in AWS DynamoDB using the Document Client

While attempting to utilize the UpdateCommand feature within the AWS DynamoDB documentation, I encountered various challenges due to its lack of detailed explanation and difficulty in implementation. My aim was to employ the update command to seamlessly t ...

Where can I find the @types for a specific lodash package?

Seeking to utilize a specific function from lodash - assignin. I have successfully installed lodash.assignin and incorporated it into my project: import assignIn = require('lodash.assignin'); However, when compiling, an error occurs: "error TS2 ...

What purpose does @ViewChild serve if we are unable to modify or interact with its properties from the Parent Component?

I have two main components - home and about. Within both of these, I am including a third component called hearts. Currently, I am manipulating the value of the 'age' property in the hearts component (initially set to '23') using @ViewC ...

the process of altering properties in vue js

After running my Vue file, I encountered the following console error. As someone new to Vue programming, I'm attempting to utilize a Syncfusion UI component to display a grid. Prop being mutated: "hierarchyPrintMode" I am unsure where to add the comp ...

Error: Unable to modify a property that is marked as read-only on object '#<Object>' in Redux Toolkit slice for Firebase Storage in React Native

Hey there! I've been working on setting my downloadUrl after uploading to firebase storage using Redux Toolkit, but I'm facing some challenges. While I have a workaround, I'd prefer to do it the right way. Unfortunately, I can't seem to ...

Is there a way to determine the height of the ion-footer?

Is there a way to obtain the height of the ion-footer element in Ionic2? I want to calculate the initial window height minus the ion-footer height, but I am currently only able to get the overall window height. I'm not interested in retrieving the ...

ngx-datatable - personalized columns featuring interactive buttons

I am currently working with a table using ngx-datatable where I have created an "actions" column for CRUD operations and added buttons. However, I am facing an issue where the selected row and its column values are not being recognized within my function. ...