Guide on activating a service in one component to close a pop-up in a separate component [angular]

In order to manage navigation in our app, we have chosen to utilize the Angular router instead of the Ionic navigation controller.

One challenge we are facing is handling navigation using the Android back button. When working with the Ionic framework, pressing the Android hardware back button triggers global ion-back-button events. Since we are not using the Ionic navigation controller, these events are only triggered by pressing the hardware back button. To address this, I have set up a global listener for ion-back-button events, which uses a navigation service to handle page-to-page navigation. The tricky part is ensuring that popups are closed before initiating page navigation.

The handler function in the app component looks like this:

backButtonEvent() {
  this.platform.backButton.subscribeWithPriority(10, () => {
    if (!this.modalService.remove()) {
      const backUrl = this.backService.getBackURL();
      if (
        !backUrl.includes("dataload") /*previous page is not dataload*/ &&
        !backUrl.includes("login") /*previous page is not login */ &&
        !this.navCtrl.url.includes("dataload") /*current page is not dataload */ &&
        !this.navCtrl.url.includes("login") /*current page is not login */
      ) {
        this.navCtrl.navigateByUrl(backUrl);
      }
    }
  });
}

And here is an example of how most modals in the app are structured:

  async showInformationModal() {
    const modalData: BasicModalData = {
      generic text: "text"
    };
    const infoModal = await this.modalController.create({
      component: BasicModalComponent,
      componentProps: {
        modalData
      },
      backdropDismiss: true,
      showBackdrop: true,
      cssClass: "modalClass"
    });
    return infoModal.present();
  }

To improve this setup, it may be beneficial to create a modal service with a function that can emit a "dismissed: true" property for the infoModal. However, the implementation of this is still uncertain.

Answer №1

The optimal solution is to implement a GuardService along with the "canDeactivate" attribute in Routes.

navigation_guard_service.ts:

@Injectable({
  providedIn: 'root'
})
export class NavigationGuardService implements CanActivate, CanDeactivate<CUSTOM_OBJECT> {
    
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean|UrlTree { /*no implementation yet */ }
    
    canDeactivate(component: CUSTOM_OBJECT, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState?: RouterStateSnapshot): boolean | UrlTree | Observable<boolean | UrlTree> | Promise<boolean | UrlTree> {
        /*
        1. Use "currentRoute" and/or "currentState" to identify the current Page
        2. Call the previously created "Page.onDeactivate(): boolean" method in that Page
        3. (here) Return TRUE to allow navigation away from the current URL, FALSE to prevent navigation, or an "UrlTree" to redirect to a different URL
        */
    }
    
}

In the Page's Module file:

@NgModule({
imports: [RouterModule.forChild(
    [
        { path: '', children: [
            { path: ROUTE_LOGIN, loadChildren: () => import('./login/login.module').then(m => m.ChooserPageModule)/*, canActivate: [NavigationGuardService]*/, canDeactivate: [NavigationGuardService] },
            { path: '', redirectTo: ROUTE_LOGIN, pathMatch: 'full' },
        ]},
        { path: '', redirectTo: ROUTE_AUTH_LOGIN, pathMatch: 'full' },
        { path: '**', redirectTo: ROUTE_AUTH_LOGIN }
    ]
)],
exports: [RouterModule],
})

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

Setting a default value and object ID in Angular's reactive forms for a select dropdown

Having an issue with validating a default value in a selector that serves as a message to select an option. The problem arises from the validation of this option, as it is linked to the object ID of another collection in the database (mongoose-express js). ...

Retrieve the array from the response instead of the object

I need to retrieve specific items from my database and then display them in a table. Below is the SQL query I am using: public async getAliasesListByDomain(req: Request, res: Response): Promise<void> { const { domain } = req.params; const a ...

Module error caused by Typescript path inconsistency

After creating a new model named "project" within the existing project, I encountered an error when attempting to import the class into another typescript file in VS2019. The specific error message thrown is as follows: "ts2307 cannot find module ' ...

Troubleshooting: Issues with Angular 2 Dependency Injection

I am facing an issue with my angular2 application that involves a simple dependency injection, but it seems to be not working correctly. Can anyone help me figure out what might be missing? Below is the error message I am encountering: EXCEPTION: Cannot ...

No control access origin header found on the request to Spring 5 WebFlux functional endpoints

I have scoured numerous resources in search of the perfect solution to my issue. In my opinion, I believe I have all the necessary components in place but I am unable to pinpoint where the problem lies. Utilizing spring 5 with WebFlux and functional endpo ...

Struggling to retrieve JSON data from MYSQL database to Android App? Reach out for assistance with

I'm currently working on an Android application that interacts with a remote MYSQL database to retrieve information using JSON data. One of the challenges I'm facing is implementing a search functionality based on the userID in the app, and then ...

The use of URL embedded parameters in @angular/http

Currently, I am utilizing a backend system that accepts search query parameters in both the ?-notation and the url-embedded format. I understand that I can use tools like URLSearchParams/RequestOptionsArgs to send requests to . However, I am curious about ...

Harness the power of the Node.js Path module in conjunction with Angular 6

I'm currently facing an issue with utilizing the Path module in my Angular 6 project. After some research, I came across a helpful post detailing a potential solution: https://gist.github.com/niespodd/1fa82da6f8c901d1c33d2fcbb762947d The remedy inv ...

Failure to set X-XSRF-TOKEN header in Angular5

After exploring several solutions, I have yet to find one that works for me. This issue on Github closely mirrors my problem (https://github.com/angular/angular/issues/20511) My setup includes Angular 5.2.5, Chrome Version 65.0.3325.146, and Spring Boot ...

Ways to transfer information from HTML form components to the Angular class

I am currently working with angular 9 and I have a requirement to connect data entered in HTML forms to the corresponding fields in my Angular class. Below is the structure of my Angular class: export interface MyData { field1: string, textArea1 ...

Error encountered in lodash.js in Angular 2 framework

I have been attempting to implement lodash for a datatable. Here are the steps I followed: First, I tried running npm install lodash, but encountered an error stating that the package could not be found After researching the issue, I attempted npm in ...

Roles in the Nebular system always have the granted status set to true by default

Hey there, I'm currently setting up Nebular to handle roles. Everything is working fine on the server side, but on the front end side, accessControl.isGranted() always returns true regardless of the role. Here's a snippet of the code I have been ...

I encountered difficulty in finding additional elements after selecting a value in the Android Date Picker

https://i.stack.imgur.com/fcrou.pnghttps://i.stack.imgur.com/EwsMH.pngWe are currently in the process of automating a mobile app using Selenium, Appium, and Java. While testing the mobile app (Android), I encountered an issue where after selecting a date ...

What is the best way to showcase development using an Angular bar graph?

Does anyone have any suggestions on how to create a visualization like the one shown in this mockup? https://i.stack.imgur.com/X72RP.png The mockup features two bar charts, each with a greyed-out area representing its own 100% or max value. For simplicity ...

In the production build, the RegEx validation is lacking and fails to accept certain characters like 0, 2, 7, a, c, u, x, and occasionally z

Incorporating Angular 15.2.10 and Typescript 4.9.5, the RegEx utilized in one of my libraries and exposed via a service is outlined as follows: private readonly _DISALLOWED_CHARS_REGEX_GENERAL = new RegExp(/^[^\\/\?\!\&\: ...

Error in Angular 2: Uncaught Promise TypeError - Unable to access property 'title' of undefined

Whenever I attempt to include a text input field with dual binding in my App, the following error pops up: ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'title' of undefined TypeError: Cannot read property 'title&ap ...

Tips on saving JSON response data to EditText in Android

Hey there! I am currently trying to retrieve the reg_no array value from the database and display it in an EditText without the need for any button clicks. I would appreciate some guidance on how to achieve this in my class file. String RegNo = Database ...

Guide to verifying a value within a JSON object in Ionic 2

Is there a way to check the value of "no_cover" in thumbnail[0] and replace it with asset/sss.jpg in order to display on the listpage? I have attempted to include <img src="{{item.LINKS.thumbnail[0]}}"> in Listpage.html, but it only shows the thumbna ...

Can you explain the variances between ngx-translate and ngx-i18next for me?

As ngx-i18next serves as a wrapper for i18next, I am curious about the specific differences in translation capabilities between ngx-translate and i18next. ...

Creating a canvas that adjusts proportionally to different screen sizes

Currently, I am developing a pong game using Angular for the frontend, and the game is displayed inside an HTML canvas. Check out the HTML code below: <div style="height: 70%; width: 70%;" align="center"> <canvas id=&q ...