Discover the steps to declare and sign up for queryParams within Angular

Let's break down this issue from two different perspectives - the user's and the developer's.

The user's perspective:

Upon clicking "Edit Server", the user expects to be able to edit the server. However, this functionality is not working as intended. To illustrate, I will provide two images showcasing this problem:

(1) https://i.sstatic.net/S6bJA.png

(2) https://i.sstatic.net/t6oKb.png

Clearly, this behavior is not desired.

Developer's perspective:

As the developer (myself), I am new to routing but will guide you through the relevant code. The issue arises when subscribing to queryParams, as it returns an empty object. This could possibly be due to the following code:

this.router.navigate(['edit', { queryParams: {allowEdit: this.server.id == 3 ? '1' : '0'}}],
{relativeTo: this.route})

It seems like this code block is not functioning as expected. Could it be related to its timing of execution? I will provide the necessary code snippets in this question thread on Stack Overflow, along with the GitHub repository link for a comprehensive view of the project.

App Module Code

// Relevant paths configuration
// Previously, ':id' and ':id/edit' were at the same level, but now 'edit' is nested under 'servers' as a child of 'server'. However, the EditComponent is not loading correctly, and its ngOnInIt is not functioning properly.
{
  path: 'servers',
  component: ServersComponent,
  children: [
    {
      path: ':id',
      component: ServerComponent,
      children: [
        {
          path: 'edit',
          component: EditServerComponent
        },
      ]
    }
  ]
},

Servers HTML Template:

<div class="list-group">
  <a
    [routerLink] = "['/servers', server.id]"
    href="#"
    class="list-group-item"
    *ngFor="let server of servers">
    {{ server.name }}
  </a>
</div>
<router-outlet></router-outlet>

Server HTML Template:

<!-- The display section handles what to display, 'edit-server' or 'server'. This part is functioning correctly. The key component is the button below -->
<div [ngSwitch]="display">
  <div *ngSwitchDefault>
    <h5>{{ server.name }}</h5>
    <p>Server status is {{ server.status }}</p>
    <button class="btn btn-primary" (click)="onEdit()">Edit Server</button>
  </div>

  <div *ngSwitchCase="1">
    <router-outlet></router-outlet>
  </div>
</div>   

Edit-Server TS:

server: {id: number, name: string, status: string};
  serverName = '';
  serverStatus = '';
  allowEdit: boolean
  id: number

  constructor(private serversService: ServersService, private route: ActivatedRoute) { }
  ngOnInit() {
    this.route.snapshot.queryParams
    this.route.snapshot.fragment
    this.route.queryParams.subscribe((params: Params) => {
      this.allowEdit = params['allowEdit'] == '1' ? true : false
    })

    this.route.params.subscribe((params: Params) => {
      this.id = +params['id']
    })

    this.server = this.serversService.getServer(this.id);
    this.serverName = this.server.name;
    this.serverStatus = this.server.status;
  }

  onUpdateServer() {
    this.serversService.updateServer(this.server.id, {name: this.serverName, status: this.serverStatus});
  }

}

Edit Server Template:

<h4 *ngIf="!allowEdit">No editing the server!</h4>
<div *ngIf="allowEdit">
  <!-- The code inside here will not execute as allowEdit is always false -->
</div>

How can I determine why the params object is empty? Feel free to explore the full project in the following GitHub repository:

https://github.com/yousefmarey12/TestingwithAngular.git

Answer №1

It appears that there is a minor issue with the router.navigate() call within the onEdit method

To fix this, make sure the first parameter is the route you want to access, represented as a string item within an array. The second parameter should be an object containing your query parameters and the relativeTo property. For example:

this.router.navigate(['edit'], { queryParams: {allowEdit: this.server.id == 3 ? '1' : '0'}, relativeTo: this.route});

By following this structure, you will be able to access all your data within the queryParms subscription.

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

Connecting JavaScript files in angular 4: A step-by-step guide

Currently, I am utilizing Angular 4 and looking to have my JavaScript file work globally. Here is how I have declared it in the index.html file: <script src="assets/js/jquery-1.11.1.min.js"></script> <script src="assets/js/bootstrap.min.js"& ...

What is the use of the mongoose $gt operator in an Express application built with

I am searching for users whose tokens have not yet expired. try { const user = await User.findOne({ resetToken: passwordToken, resetTokenExpiration: { $gt: Date.now() }, _id: userId, }); if (!user) { throw new NotFoundEr ...

How to retrieve data from the resolve function in an Angular 2 component

How can I access the resolved data in an Angular 2 migrated component? I have an Angular JS app.config set up with routing that loads the necessary Angular 2 migrated component. .state('users.list', { url: '/users/list', templ ...

Is having only one FCM token sufficient for storing data from multiple devices?

I'm currently working on an Angular website and looking to send push notifications to users subscribed on both desktop and mobile. I am utilizing Firebase Cloud Messaging for this purpose and wondering if storing a single FCM token will suffice for se ...

Encountering a glitch with ng2-pdf-viewer on Angular version 13.2.2 and Ionic version 6

Issue reported: The following error message is encountered when trying to set up the PDF viewer: Error: Setting up fake worker failed: "Cannot load script at: https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.5.207/pdf.worker.min.js". It is observed while ...

I recently updated all my projects to Angular 14, but when I tried to install a package using `npm i`, it still

The challenge at hand I encountered an issue with my two Angular projects. The first project serves as a library utilized by the second project. I recently upgraded both projects to Angular 14 following this guide. However, after running an npm i on the ...

What are the best ways to increase the speed of eslint for projects containing a high volume of files

My git repository contains around 20GB of data, mainly consisting of JSON/CSV/YAML files. Additionally, there are scattered TypeScript/JavaScript (.ts/.js) files among the data files. As the repository has grown in size, I encounter a significant delay eve ...

Utilizing Angular 4 alongside ng-sidebar to incorporate the class "right"

Just started using ng-sidebar in my Angular 4 project, but I'm a bit lost on where to place the "ng-sidebar--right" class. Could someone please guide me through this small issue (I'm new to this, so apologies in advance). Here's a snippet of ...

Starting PM2 with multiple instances can be achieved by following these steps

While running my nodejs code with PM2, I encountered a requirement for multiple instances of nodejs executing the same code. To address this need, I created a script named "myscript.sh": cd ~/myproject PM2_HOME='.pm2_1' /usr/local/bin/node /u ...

Is bundling a Node.js backend a wise decision or a mistake?

Just a thought that crossed my mind - I understand the advantages of bundling client-side code, but what about bundling server-side code with Browserify/Webpack? Is this considered a best practice? ...

Ways to resolve the angular error "Encountering an unhandled exception: Unable to locate module 'typescript' "?

I'm encountering errors when running ng serve. I've attempted the following code as well, but I'm still facing the same error: npm install -g typescript https://i.sstatic.net/Gyi71.png Error displayed in text format D:\xampp\htd ...

Angular Unit Test: Received 1 argument instead of the expected 3

Currently, I am in the process of unit testing an Angular application. This is my first time venturing into Angular Unit Testing. To save time, I downloaded the angular app from here. As a beginner in Unit Testing, I watched some informative videos on the ...

The blur event in Angular Material's mat-date-range-input does not trigger if the End Date is not selected

I am currently utilizing Angular 15 along with Angular Material 14. The code for the DatePicker control is shown below. <mat-form-field class="datepicker-widget" appearance="fill"> <mat-date-range-input [formGroup]="d ...

Ways to incorporate only essential UI elements in @angular/material

In the process of creating my Angular application, I am looking to streamline its size. Currently, my app relies on Angular Material, but upon inspecting the node_modules folder, I realized that there are unused UI components such as autocomplete and check ...

Is it possible to remove a complete row in Angular 2 using Material Design

JSON [ { position: 1, name: 'test', value: 1.0079, symbol: 'HHH' }, { position: 2, name: 'test2', value: 4.0026, symbol: 'BBB' }, { position: 3, name: 'test3', value: 6.941, symbol: 'BB' }, ...

Developing an npm package for storing a communal instance

I am interested in developing an npm library that can be initialized with a specific set of keys and then utilized throughout an entire project. Here is an illustration of how I envision its usage: In the main component or page import customLib from &quo ...

Creating a mongoDB query that matches elements in an array of subdocuments with elements in a Typescript Array

In my database, I have stored various Events using mongoDB. Each event comes with multiple fields, including an array of genres, which consists of subdocuments like {genre and subGenre}. For instance, an event could be classified as {genre: "music", subGe ...

The perplexing actions of Map<string, string[]> = new Map() have left many scratching their heads

I encountered an issue while trying to add a value to a map in my Angular project. The map is initially set up using the following code: filters: Map<string, string[]> = new Map(); However, when I attempt to add a value to this map, it starts displa ...

What is preventing the exclusion of the null type in this specific situation within Typescript?

type NonNullableCopy<O> = { [p in keyof O] -?: O[p] extends null | undefined ? never : O[p]; }; type Adsa = {a?: number | null} type Basda = NonNullableCopy<Adsa> let asd : Basda = { a: null // Still valid. No errors } Although it see ...

Guide to setting headers to application/json in Angular 2

I've been attempting to send an HTTP post request in Angular 2, but I'm facing difficulties setting the headers to content type application JSON. This is my current code: login(url, postdata) { var headers = new Headers({'Content-Type&a ...