Strange behavior observed when redirecting in an Angular component inside an async function block

My app is receiving FCM messaging notifications successfully, but I'm facing an issue when trying to trigger a router navigation. Specifically, I want to display a page that mimics the standard Android incoming call screen when a call notification is received. I have set up a listener for pushNotificationReceived as shown below:

 await PushNotifications.addListener('pushNotificationReceived', notification => {
      this.logger.info(`[PUSH NOTIFICATION] - Push notification received: [Title: ${notification.title}, Body : ${notification.body}]`);

      if (notification.data && notification.data.IncomingCall) {
        this.logger.info(`INCOMING CALL FROM ${notification.data.CallerName}`);
        this.router.routeReuseStrategy.shouldReuseRoute = () => false;
        this.router.onSameUrlNavigation = 'reload';
        this.router.navigate(['/incomingcall']);
      } else {
        this.showNotificationDialog(notification.title || '', notification.body || '');
      }
    });

However, when this code is executed, the screen does not change as expected. It appears to be somewhat unresponsive, with controls and clicks not functioning properly.

I enabled router debugging and observed that routing is indeed happening, but it seems to stall, as the component's ngInit logging does not display.

Line 1 - Msg: %c2022-03-23T13:43:07.094Z INFO [main.1554ef6f3488783a.js:1:377716] color:gray [PUSH NOTIFICATION] - Push notification received: [Title: Incoming call, Body : undefined]
 Line 1 - Msg: %c2022-03-23T13:43:07.095Z INFO [main.1554ef6f3488783a.js:1:377850] color:gray INCOMING CALL FROM Frank
 (Router Event logs follow...)

My app.component.html file consists of a router-outlet with the Home.Component serving as the layout, which contains its own router-outlet. Here are my router module configurations:

const routes: Routes = [
  {
    path: 'incomingcall',
    component: IncomingCallComponent
  }, 
  {
    path: '',
    component: HomeComponent,
    children: [
        (Other route configurations...)

Upon inspecting the router-outlet tags in each component, I noticed that although the new page is almost rendering correctly within the app.component router outlet, the page within the home.component router-outlet continues to show simultaneously. It appears as below:

<Appcomponent-router-outlet>
    <HomeComponent-router-outlet>
        <Contacts Page>
    </HomeComponent-router-outlet>
        <IncomingCall Page>
</Appcomponent-router-outlet>

I attempted to replicate this behavior on StackBlitz, but I was unsuccessful in doing so. I suspect this may be due to the limitations of reproducing the PushNotification.addListener method accurately. For reference, you can view the StackBlitz project here.

Answer №1

After some troubleshooting, I discovered that the solution was to execute the router navigate function within the ngZone context, as shown below:

this.zone.run(() => this.router.navigateByUrl('/incomingcall'));

It seems that this approach triggers a broader change detection process, potentially resolving issues at a higher level.

Hopefully, this tip will be beneficial to others facing a similar issue.

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

Angular - The Architectural Design of Components

I am looking to create a component that can serve as a template for multiple components, all sharing the same methods. How can I convert this into a blueprint? My goal is to avoid duplicating methods across all other components. Instead, I only want to ov ...

Step-by-step guide on deploying your Nestjs API on Google App Engine

Encountering a hurdle while trying to deploy my nestjs api on Google App Engine has left me puzzled. Despite initializing my google cloud project with the google sdk, an error thwarted my progress. To tackle this challenge, I made key adjustments in my cod ...

Angular appears to be having trouble with localStorage functionality

Having an issue with my service that interacts with a local NOTES object array using localStorage. Whenever the page refreshes, the previously entered data is lost and only the initial data in the const NOTES array remains. Can't seem to figure out wh ...

What are the steps to properly format a Typescript document in Visual Studio Code?

After experimenting with several plugins, I have not been able to achieve the same formatting as Sublime Text. Here is an example of the result after formatting. Ideally, I would like to maintain the properties in the same line if possible. Thank you. VSc ...

Exploring methods to validate a Reactive Form in Angular 10+ by incorporating two groups within the formBuilder.group

I am looking to implement form validation with two separate groups within the main formBuilder.group. I am unsure of how to access the 'errors' value in my HTML [ngClass]. component.ts: createForm(): void { this.myForm = this.formBuilder ...

How can you utilize Angular Signals in combination with HostBinding to dynamically update styles?

Within a component called app-test, the following code is present: @Input({ transform: booleanAttribute }) reverse: boolean = false; @HostBinding('style.flex-direction') direction: string = this.reverse ? 'column-reverse' : &ap ...

Error message: Material Design UI - The type 'string' cannot be assigned to the type Icon

I am currently working on a component that is responsible for returning the specific icon based on the prop that is passed. Here is a simplified version of how it works in my application: import * as icons from "@mui/icons-material"; interface I ...

A step-by-step guide on reading/loading a JSON file using Typescript

I'm fairly new to Typescript and I'm attempting to parse a simple JSON file using Typescript. After searching online and testing different solutions, I still haven't been able to find a straightforward code snippet that reads a local JSON fi ...

Retrieving and adding the content of a CSRF token created by Django within Angular applications

I am encountering difficulties with the CSRF integration between Django and Angular. I previously posted a more general inquiry here. The issue is that authenticated users cannot send post requests from the front-end, although they can do so successfully v ...

"Implementing initialization without the need for jQuery with the next.material

Today, I had the chance to explore the 1.0 alpha version of materializecss. As someone who works with Angular, I found myself utilizing components that require jQuery initialization such as Side Nav. The documentation mentions a way to initialize them usi ...

Angular routing system using hash symbol to navigate to different routes without considering the

As I work on developing an extension, I encountered a challenge when trying to open the popup to a specific route. Despite providing the URL moz-extension://adf...as/dist/extension/index.html#/home/otherpage The popup seems to ignore the #/home/otherpage ...

Encountered problem in Angular with Cognito: Unable to access property 'user' of null in authorization.service.ts at line 29

For the purpose of understanding, I am working on implementing a proof of concept involving AWS Cognito and API Gateway. I have customized the UserPoolId and ClientId in the authorization.service.ts file based on the instructions in a video tutorial. The a ...

Identifying whether an Angular component has been loaded through a template or a route: Ways to distinguish

How can I determine how an Angular component was loaded? I have a component that can be accessed through a route or loaded within another component's template, and I want to be able to identify the loading method for the purpose of animations. ...

Error: Unexpected top-level property "import/order" in ESLINT configuration

I'm in the process of setting up a guideline to include one blank line between internal and external imports. .eslintrc.json: { "parser": "@typescript-eslint/parser", "env": { "es6": true, " ...

How to trigger a click event in React using TypeScript and material-ui library

Currently, I am facing an issue when trying to update the value of material-ui TextFields from the store. When manually typing inside the field, everything works fine as expected with the handleChange() and handleBlur() functions handling the events. Howev ...

The presence of v-if does not depend on the model value to toggle the element

I have a scenario where I want to hide the dropdown menu for US states if a different country other than the US is selected. The code snippet I am using to achieve this functionality is shown below: <b-row v-for="demo in demographics" :key=&qu ...

My goal is to prevent users from using the Backspace key within the input field

Let's say we want to prevent users from using the backspace key on an input field in this scenario. In our template, we pass the $event like so: <input (input)="onInput($event)"> Meanwhile, in our app.component.ts file, the function ...

The program is requesting an expression involving the user's username

https://i.stack.imgur.com/tf1QD.png What is causing the issue with trying to use user.username? as an expression? While user.username returns a string of the User's username, I am unable to index it into listOfPlayers[]. client.on("messageReacti ...

Tips for resolving issues with mat-autocomplete during scrolling

When I open the mat-autocomplete and scroll down the page, I would like for the mat-autocomplete to stay in place. ...

Executing a service request in Angular 2 using a versatile function

I have a function that determines which service to call and a function template for calling the service returned by that function. This function makes HTTP requests using http.get/http.post, which return an Observable and then perform a map operation on th ...