Angular's queryParams do not appear to properly connect with the query parameters

My code seems to have a mistake somewhere, but I can't figure it out. In my

[queryParams] = "{allowEdit: server.id == 3 ? 1 : 0}"
, the params object is empty when I subscribe to it in the edit-server component. Why is it empty and how do I add allowEdit to it? Maybe the issue lies in an incorrect path? Let me provide more details about relevant paths.

Here is the code snippet:

ServerS Template

  
      <a
        [routerLink] = "['/servers', server.id]"
        [queryParams] = "{allowEdit: server.id == 3 ? 1 : 0}"
        href="#"
        class="list-group-item"
        *ngFor="let server of servers">
        {{ server.name }}
      </a>
    <router-outlet></router-outlet>

Server Template:

<h5>{{ server.name }}</h5>
<p>Server status is {{ server.status }}</p>
<button class="btn btn-primary" (click)="onEdit()">Edit Server</button>

Server TS:

export class ServerComponent implements OnInit {
  server: {id: number, name: string, status: string};
  id: number

  constructor(private serversService: ServersService, private route: ActivatedRoute, private router: Router) { }

  ngOnInit() {
    this.id = +this.route.snapshot.params['id']
    this.server = this.serversService.getServer(this.id)
  
    this.route.params.subscribe((params: Params) => {
      this.server = this.serversService.getServer(this.id)

    })

  }

  onEdit() {
    this.router.navigate(['edit'], {relativeTo: this.route})
  }

}

Edit Server TS:

export class EditServerComponent implements OnInit {
  server: {id: number, name: string, status: string};
  serverName = '';
  serverStatus = '';
  allowEdit: boolean

  constructor(private serversService: ServersService, private route: ActivatedRoute) { }
  ngOnInit() {
    this.route.snapshot.queryParams
    this.route.snapshot.fragment
    this.route.queryParams.subscribe((params: Params) => {
      console.log(params['allowEdit']) // for some reason, params['allowEdit'] gives us undefined
      this.allowEdit = params['allowEdit'] == 1 ? true : false
    })
    this.route.fragment.subscribe((params: string) => {
    
    })
    //
    this.server = this.serversService.getServer(1);
    this.serverName = this.server.name;
    this.serverStatus = this.server.status;
  }
}

Please note that some code blocks may be irrelevant, but if you need more information, feel free to ask. Here's my folder structure and AppModule paths for reference.

App Module:

const appRoutes: Routes = [
  {
    path: 'users',
    component: UsersComponent,
    children: [ {
      path: 'users/:id/:name',
      component: UserComponent
    }]
  },
  {
    path: '',
    component: HomeComponent
  },

  // The ones below are the important ones
  {
    path: 'servers',
    component: ServersComponent,
    children: [  {
      path: ':id/edit',
      component: EditServerComponent
    },
    {
      path: ':id',
      component: ServerComponent
    }]
  },
  
]

Relevant Folder Structure

https://i.sstatic.net/zI47N.png

Answer №1

You've hit the nail on the head: the allowEdit parameter is only sent to the route servers/:id

If you wish to retrieve it from the servers/:id/edit component, you must define it as a child of the servers/:id route:

const appRoutes: Routes = [
  // other routes
  {
    path: 'servers',
    component: ServersComponent,
    children: [
      {
        path: ':id',
        component: ServerComponent,
        children: [
          {
            path: 'edit',
            component: EditServerComponent
          },
        ]
      }
    ]
  },
]

In the EditServerComponent, you'll need to access the data through the parent route:

this.route.parent.queryParams.subscribe(...)

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

Having trouble accessing a JSON object with Typescript in an Angular 2 project

Something strange is happening with my code. I am working with a JSON object: {"login":"admin","name":"Admin"} And this is the relevant part of my code: private _userData: User; ... private getUserData() { this._userInfoService.getUserInfo() ...

Dealing with AOT challenges when integrating ng2-bootstrap into Angular 2 applications

I'm currently developing an Angular 2 app and encountering an error when attempting to create a bundle with AOT compilation following the guidelines in Angular 2 documentation here. The dependency error I'm facing is as follows: Refer to this ...

What is the best approach to implement a recursive intersection while keeping refactoring in consideration?

I'm currently in the process of refactoring this code snippet to allow for the reuse of the same middleware logic on multiple pages in a type-safe manner. However, I am encountering difficulties when trying to write a typesafe recursive type that can ...

Angular ngFor directive is unable to iterate through nested data

I am struggling to make angular show some important information. Below is the necessary data: information = [ { title: 'title1', details: [ { id: 1, description: 'some info' }, ...

Angular 5 Component persists despite change in child route

Hello, I'm facing an issue with my Angular 5 App. I have created a simple app with component routing structured as follows: { path: '', component: SetupComponent, pathMatch: 'full' }, // landing page { path: 'setup', com ...

Employing union types and type guards within templates while utilizing ngForOf in Angular

When utilizing array: (A | B)[] within an *ngFor, it appears that the only option is to use $any() extensively throughout the template. Is there a more efficient way to handle this situation? I've managed to bypass typing altogether by using $any(), ...

What is the best method for accessing a store in Next.js with Redux Toolkit?

Currently, I am working on incorporating integration testing for my application using Jest. To achieve this, I need to render components in order to interact with various queries. However, in order to render a component, it must be wrapped in a Provider to ...

Tips for handling various HTTP requests until a response is received

For my application, I have a need to make multiple http calls before proceeding to create certain objects. Only after all the http requests have received responses from the servers can I process the results and construct my page. To handle this scenario, ...

Leveraging the power of ReactJS and TypeScript within a Visual Studio environment for an MVC5 project

I am currently working on creating a basic example using ReactJS and TypeScript in Visual Studio 2015. Despite following several tutorials, none of them have met my specific requirements or worked as expected. My goal is to develop components as .tsx fil ...

Angular Compilation Blocked Due to Circular Dependency Error

Currently, I am utilizing WebStorm as my IDE to work on a personal project that I envision turning into a game in the future. The primary goal of this project is to create an Alpha version that I can showcase to potential employers, as I am actively seekin ...

Experiencing difficulties with PrimeNg installation on Angular 12.1.4 due to an npm error

I'm facing an issue while trying to integrate PrimeNG into my project. I encountered a strange error and I'm unsure about how to resolve it. Can anyone offer some assistance? The Angular version currently installed on my machine is 12.1.4. 205-18 ...

Setting up state using the useState hook in a Typescript environment

At some point in the future, the state will be updated using the useState hook with an array of objects. The interface for this array of objects will look like this: export interface DataSource { dataPiont: Array<DataPoint>; } export interface Dat ...

Prevent Angular 4 Component Reloading

I need my component to remain stable without reloading every time a new page is accessed. Currently, it reloads on each page change which disrupts the functionality. This issue is particularly evident in the Header section where there is a Marquee that rel ...

I'm struggling to include a link in my project card component - I've tried using both the Link tag and anchor tag, but so far, I haven't been successful in

I am having trouble getting the link tag to work properly in my UI. I have tried using both the link and anchor tags, but neither seems to be functioning as expected. Can someone please advise on how to fix this issue? https://i.sstatic.net/tAD7C.png I w ...

Traversing the enum's keys poses a challenge in terms of typing

Imagine you need to display all values of an enum enum AnEnum { a = 'a', b = 'b' } const keys = Object.keys(AnEnum); keys.forEach(key => { console.log(AnEnum[key]); }); This results in the following error message: ...

Struggling with TypeScript Errors while Extending Theme Colors in Material UI React using TypeScript

Just started with typescript and feeling a bit lost, can someone offer some guidance? I'm working on a React project using material-ui with typescript. To add a new color the correct way, it needs to be added to a theme: const theme = createMuiTheme({ ...

The Angular Material dialog fails to display content when triggered within an event listener in Google Maps

Within my project, I am utilizing Angular 6.0.6 and Angular Material 6.3.0. One issue I have encountered is with a dialog component that I have added to the entryComponents in the app module. Strangely, when I attempt to open this dialog within the rightcl ...

Can you identify the category of the new Set containing the elements 1, 2, and 3?

As a beginner in TypeScript, I'm currently exploring the appropriate type for JavaScript's new Set([1, 2, 3]), but my search has been unsuccessful so far. For instance: const objNums: {[key: string]: number} = {one: 1, two: 2, three: 3}; const a ...

Deriving types from object combinations

Can the Foo type be 'flattened' to return { A?: string; B? number } in the code snippet below? type Foo = { A: string } | { B: number } type Flatten< T, Keys extends keyof T = T extends any ? keyof T : never, > = { [K in Keys]?: T[K] } ...

Combining the JSON code coverage reports generated by both Cypress and Karma does not yield an accurate outcome

In my angular project, I am testing it using the built-in unit testing tool (karma) and Cypress. My goal is to combine the code coverage reports from both tests. I have successfully set up the coverage configurations and merged the outputs using `nyc merg ...