Implementing multiple route parameters in Angular 6

I have set up two parameterized routes for handling mails.

 { path: 'mails', component: MailsComponent, canActivate: [AuthGuard] },
 { path: 'mails/:label', component: MailsComponent, canActivate: [AuthGuard] },
{ path: 'mails/folder/:folder', component: MailsComponent, canActivate: [AuthGuard] }

Within the component, I need to access route parameters based on certain conditions.

ngOnInit(): void{ 
    if (this.googleAuth.stateFlag) {
      // handle labels
      this.route.paramMap.subscribe(route => {
        this.label$ = route.get('label');
        this.googleAuth.selectedEmailLabel(this.label$);
      });
    }
    else {
      // handle folders
      this.route.paramMap.subscribe(route => {
        this.folder$ = route.get('folder');
        console.log('folder handle:', this.folder$);
        this.googleAuth.selectedEmailFolder(this.folder$);
      });
    }
}

Despite the condition being in place, the else block is always executed.

Answer №1

The reason for the issue may be that ngOnInit is called only once during the component's lifecycle, while the component can be reused multiple times when there are route changes. To address this, you can subscribe to paramMap and handle the logic within it like so:

ngOnInit(): void{ 
  this.route.paramMap.subscribe(route => {
    if (this.googleAuth.stateFlag) {
      this.label$ = route.get('label');
      ...
    } else {
      this.folder$ = route.get('folder');
      ...
    }
  });
}

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

Ways to verify the functionality of this specific custom hook (useRef)

Can anyone help me figure out how to pass the useRef as a parameter for testing this custom hook that uses ElementRef from React? import { MutableRefObject, useEffect, useState } from "react" export default function useNearScreen(elementRef: ...

Is there a way to determine the present date within a template?

In my component, I am working with an object that contains a timestamp. What I aim to achieve is to dynamically check this timestamp in the template at runtime. For instance, I want to display the online status of a member by showing a green dot if they a ...

Misunderstanding between Typescript and ElasticSearch Node Client

Working with: NodeJS v16.16.0 "@elastic/elasticsearch": "8.7.0", I am tasked with creating a function that can handle various bulk operations in NodeJS using Elasticsearch. The main objective is to ensure that the input for this funct ...

The absence of @angular/compiler in the bundle file is causing an issue with Angular es

I've developed a shell application that operates using and https://github.com/systemjs/systemjs to manage its various micro-frontends. Recently, I created a new Angular application and aimed to integrate it with the esBuild builder tool. Upon runni ...

Identifying the various types in Typescript

In the process of developing a solution for Excel involving data from an Office API, I encountered the challenge of distinguishing between different types that a function can return. Specifically, the data retrieved as a string may belong to either a "Cell ...

Deploying Angular to a shared drive can be done in a

My angular.json file contains the following line: "outputPath": "Y:\Sites\MySite", After running ng build, I encountered the error message: An unhandled exception occurred: ENOENT: no such file or directory, mkdir 'D:& ...

The initial attempt at using Transloco translate is often unsuccessful

Here is my customized Transloco configuration: @Injectable({ providedIn: 'root' }) export class TranslocoHttpLoader implements TranslocoLoader { constructor(private http: HttpClient) {} getTranslation(lang: string) { return this.http.get ...

Ways to implement modifications to two separate input fields utilizing a single function

I am in the process of developing a performance comparison widget using Angular. The purpose of this widget is to compare the performance of the current Calendar year with the Previous Calendar Year, as well as the performance from the current Year-to-date ...

Tips for displaying only the initial 15 characters of a text value

The content extracted from a .ts file is being displayed on the home.html page. I am aiming to display only the initial 15 characters followed by 3 dots (...). Despite my efforts, the following code snippet is not functioning as expected: home.html < ...

Access the data within a jsonArray using Cypress

I'm dealing with a test.json file that contains a jsonArray [{ "EMAIL": "email_1", "FIRST_NAME": "Daniel" }, [{ "EMAIL": "email_2", "FIRST_NAME": "John" }] ] I'm trying to figure out how to use cypre ...

Extracting data from the Sanity API response in JSON format using Typescript

Struggling with extracting information from a Sanity Client API call and decoding the resulting JSON data. Can someone guide me on how to access specific values? Below is the output of the API call: [ { slug: { current: "test-post", _type: ...

How can debugging in Chrome be achieved using Typescript?

How is it possible to debug TypeScript in Google Chrome when the browser only understands JavaScript? I find myself debugging my TypeScript files within my Angular project, which was created using Angular CLI, through the Chrome developer tools. However, ...

Guide on bringing a function or its result from TypeScript (.ts) to JavaScript (.js)

I am working with a TypeScript file named a.component.ts import { Injectable } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { HttpClient } from '@angular/common/http'; @Injectable({ ...

Preventing angular router events from being logged in the console

In the process of developing an angular application, I have encountered a challenge with the {RouterModule} from @angular/router. Although I rely on console.log to troubleshoot my app, the router module has unleashed a flurry of router events in the conso ...

Having trouble with Angular's ActivatedRoute and paramMap.get('id')?

Currently, I am attempting to retrieve information from my server using the object's ID. The ID can be found in the URL as well: http://xyz/detail/5ee8cb8398e9a44d0df65455 In order to achieve this, I have implemented the following code in xyz.compo ...

Retrieving a URL from an API with ngIf and then reusing the returned value

Allow me to provide a clear explanation of the situation: I am utilizing an API call where I input IDs and receive a downloadURL in return. Currently, I have implemented this as a Promise in my Service: Within fileClientService: public async getFile(aID ...

The jasmine and protractor combination couldn't locate the specified element using its tagname

Why does my test keep failing in Protractor when trying to find the element by tag name? it('should display the test component', async () => { await browser.get('/trade') element(by.tagName(('test-component'))).isP ...

Strategies for iterating over an array in React with TypeScript

I'm currently working on looping through an array to display its values. Here's the code I have: ineligiblePointsTableRows() { return this.state[PointsTableType.INELIGIBLE].contracts.map(contract => { return { applied: (&l ...

Guide to building a container/palette for buttons in Angular 8

I am looking to design a unique container or palette to house some of the buttons on my webpage, allowing me to customize their background color and add other effects. Here is an example of what I am envisioning, with 3 buttons (Question, Action, Output) ...

Applying specific data types to object properties for precise value identification in Typescript

I've been working on creating a dynamic settings menu in TypeScript using the following data: const userSettings = { testToggle: { title: "Toggle me", type: "toggle", value: false, }, testDropdow ...