The detection of my query parameters is not working as expected

Creating an Angular application that dynamically loads a different login page based on the "groupId" set in the URL is my current challenge. The approach involves sending each client a unique URL containing a specific "groupId" parameter. A template is then utilized to fetch text and images from the firebase repository using this particular company's groupId.

I initially attempted to use query parameters in the following manner:

(Within my component):

  ngOnInit() {
    console.log('test');

    console.log(this.activeRoute.queryParams);
     this.activeRoute.queryParams
    .subscribe(params => {
      this.groupId = params.groupId;
   })
   console.log(this.groupId);
   if (this.groupId === undefined) {
    this.router.navigate(['/login/locked']);
   }
  }

(and the routes within the parent component)

const routes: Routes = [
  {
    path: 'login',
    component: LoginComponent,
    children: [
      {
        path: '', component: SignInComponent,
      },
      {
        path: 'signup', component: SignUpComponent,
      },
      {
        path: 'locked', component: LockScreenComponent,
      },
      {
        path: 'password-rest', component: PasswordResetComponent,
      }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class AuthPagesRoutingModule { }

Despite implementing this, I continue to receive an "undefined" result when checking this.groupId after entering

www.example.com/login?groupId=FACEBOOK235
into the address bar (which leads me to the locked screen). Is there a crucial element I am overlooking?

Answer №1

since your if statement is located outside the subscribe function, the code may not execute as expected due to the asynchronous nature of the queryParams observable. To resolve this, consider the following revised code:

ngOnInit() {
    console.log('test');

    console.log(this.activeRoute.queryParams);
     this.activeRoute.queryParams
    .subscribe(params => {
      this.groupId = params.groupId;
      console.log(this.groupId);
      if (this.groupId === undefined) {
       this.router.navigate(['/login/locked']);
      }
   })
  }

(UPDATE) Printing out the complete parameter list yields:

closed: false
destination: BehaviorSubject {_isScalar: false, observers: Array(0), closed: false, isStopped: false, hasError: false, …}
hasError: false
isStopped: false
observers: []
operator: MapOperator {thisArg: undefined, project: ƒ}
source: BehaviorSubject {_isScalar: false, observers: Array(0), closed: false, isStopped: false, hasError: false, …}
thrownError: null
_isScalar: false
[[Prototype]]: Subject
complete: ƒ complete()
constructor: class AnonymousSubject
error: ƒ error(err)
next: ƒ next(value)
_subscribe: ƒ _subscribe(subscriber)
[[Prototype]]: Observable
asObservable: ƒ asObservable()
complete: ƒ complete()
constructor: class Subject
error: ƒ error(err)
lift: ƒ lift(operator)
next: ƒ next(value)
unsubscribe: ƒ unsubscribe()
_subscribe: ƒ _subscribe(subscriber)
_trySubscribe: ƒ _trySubscribe(subscriber)
Symbol(rxSubscriber): ƒ [_internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_2__.rxSubscriber]()
[[Prototype]]: Object

Answer №2

When working with asynchronous observables, it's important to be mindful of where you access your properties. One common mistake is placing if conditions outside the subscribe method, which can lead to undefined values being retrieved. To avoid this issue, make sure to access necessary properties within the subscribe method itself.

ngOnInit() {
     this.activeRoute.queryParams
    .subscribe(params => {
      this.groupId = params.groupId;
      console.log(this.groupId);
      if (this.groupId === undefined) {
         this.router.navigate(['/login/locked']);
      }

   })   
  }

Answer №3

When using

this.activeRoute.queryParams.subscribe
, keep in mind that it is asynchronous. This can lead to console.log reporting undefined. To address this, make sure to add a check inside the subscribe function, like this:

this.activeRoute.queryParams
  .subscribe(params => {
    this.groupId = params.groupId;
    console.log(this.groupId);
    if (this.groupId === undefined) {
      this.router.navigate(['/login/locked']);
    }
})

Additionally, consider implementing Guards for extra security measures. You can learn more about Guards by visiting: https://angular.io/guide/router-tutorial-toh#milestone-5-route-guards. By utilizing a CanActivate guard that returns true or a URL tree, you can achieve the desired functionality.

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

What steps should we take to ensure that the container beside the fixed left navigation bar is responsive?

Currently, I am working on creating a user interface that features a fixed navigation bar on the left hand side and a responsive content window. Here is what I have implemented so far: <div style="width: 15%; float: left; display: inline;"> <na ...

Create Functions to Encapsulate Type Guards

Is it possible to contain a type guard within a function as shown below? function assertArray(value: any): void { if (!Array.isArray(value)) { throw "Not an array" } } // This doesn't work function example1(value: string | []) { a ...

The issue with the Angular 5 HttpClient GET-Request not closing persists

Currently, I am utilizing an Http-GET request to fetch JSON data from my backend service. Service: public storedCategories: BehaviorSubject<Category[]> = new BehaviorSubject(null); constructor() { const subscription = this.http.get&l ...

Implementing child components rendering in a React application using TypeScript

Just a little background information: I am attempting to build a carousel with pagination using ReactJS. Here is the code snippet I currently have: interface HTMLCarouselT { children: Array<JSX.Element> size: number; } const HTMLCarousel = ({ch ...

Setting the date of the NgbDatePicker through code

I have implemented two NgbDatePicker components in my project: input( type="text", ngbDatepicker, #d="ngbDatepicker", [readonly]="true", formControlName='startDate', (dateSelect)='setNew ...

The Angular application's "wait" dialog fails to appear

I'm currently setting up a dialog that includes a mat-spinner while the page data is loading in an Angular v14 project. Instead of using a basic spinner, I opted for a dialog because I need to pass some additional information within it. However, I&apo ...

Allow only numerical values through an ion-input in Ionic 4, preventing the input of letters and special characters

I am currently developing an application in Ionic 4 that requires users to enter only integer numbers (0-9). I need to prevent any other characters such as alphabets, dots, or plus signs from being entered. However, the methods I have tried so far have not ...

Replacing child routes with an Angular wildcard route

I'm facing an issue with integrating a module named "host" into the app-routing.module. The problem I encountered is that the wildcard route takes precedence over loading the Host component, leading to the display of the PageNotFoundComponent instead. ...

When you call Subscribe(), you will receive the output "complete: () => void; 'complete' is defined in this context. What exactly does this signify?

Currently, I am following a tutorial and after meticulously checking and rechecking, I can confidently say that my code matches exactly with the one the professor is using. The tutorial involves creating a simple Single Page Application in Angular using Ty ...

TS2339: The attribute 'size' is not present on the 'string' data type

Within my Typescript file, I have the following line: return stringToValidate.length <= maxLength; Despite the code executing without issues, an error is displayed: TS2339: Property 'length' does not exist on type 'string'. I am cu ...

Explore the Ability to Monitor Modifications to an Object's Property in Angular2/Typescript

Can we track changes to an object's field in Angular2/Typescript? For instance, if we have a class Person with fields firstName, lastName, and fullName, is it feasible to automatically modify fullName whenever either firstName or lastName is altered? ...

How to eliminate arrows in ngx-bootstrap datepicker?

I recently started working with Angular and Bootstrap and I'm facing an issue. I am using a ngx bootstrap datepicker, but I would like to remove the standard arrows on the buttons of the datepicker calendar. Here is a screenshot of the problem: https ...

Guide on how to utilize jest for mocking MongoDB manager in typescript

Is there a way to return a mongodb.connection.db() type value and mock its collection for testing purposes? I have implemented a mongoClient connection and use its db() function. If everything is set up correctly, I should be able to access the collections ...

How can I add a parameter to a JSON URL in Angular?

I'm looking to enhance my URL by adding a new parameter, but I'm unsure of the steps needed. ts.file route(name:string) { this.router.navigate(['/homepage', (name)]); console.log('name); } service private url1 = './assets/ ...

Using a method call instead of a property for the ngFor directive can lead to an infinite loop of loading

Within my template, I have included the following code: <a *ngFor="let item of navItems" [routerLink]="item.link" routerLinkActive="active" class="navigation-item" [ngClass]="{'enabled': item.enabled}" > <span class="color ...

Optimal approach for customizing the appearance of child components based on the parent component

I'm curious about the optimal method for styling child components based on their parent component. For instance, I want to design a list component that can be utilized in both a dropdown popup and a toolbar, each with its own unique style. There are ...

Error: The identifier HTMLVideoElement has not been declared

Encountering an issue while attempting to build my Angular 9 Universal project for SSR: /Users/my-project/dist/server.js:28676 Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__metadata"])("design:type", HTMLVideoElement) ReferenceError: HTMLVideoElem ...

Looking for a sublime plugin that will enhance your angular view template?

When using Sublime Text with Angular (2/4), everything works great until I'm working in the view template file. The interpolation doesn't offer auto-completion for class properties that support the view, unlike what I've seen in VS Code. Ar ...

Following the Angular 6 update, a new error message "Error: Expected to find an ngsw-config.json configuration file" appears when running the ng build --prod command

After completing the update process, I encountered an issue during the build where the following error message appeared. Error: Expected to find an ngsw-config.json configuration file in the /Users/nathanielmay/Code/firebaseTest folder. Either provide ...

Encountering a ReferenceError while attempting to implement logic on a newly created page

I've been experimenting with building a website using the Fresh framework. My goal was to add a simple drop-down feature for a button within a navigation bar, but I'm struggling to figure out where to place the necessary code. I attempted creatin ...