4

I would like to read optional URL parameters, no matter query or matrix parameters, in the component bootstrapped by Angular, this while/in ngOnInit().

As far as I understood, "ActivatedRoute" is not available in a component not loaded in outlet, so with an index.html like:

<body>
  <app-root>Loading...</app-root>
</body>

and app.module.ts file containing:

bootstrap: [AppComponent]

if, and how, would it be possible to access a parameter from i.e. http://localhost:4200/my-component/id;param1=abc ?

@Component({
  selector: 'app-root',
  template: '<router-outlet></router-outlet>',
  styles: []
})
export class AppComponent implements OnInit {

  constructor(private router: Router) {
    ... ?
  }

  ngOnInit(): void {
    ... ?
  }
}

2 Answers 2

0
import { Component, OnDestroy, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';

export class AppComponent implements OnInit, OnDestroy {
  private var1: string;
  private var2: string;
  private sub: Subscription;

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

  ngOnInit() {
    // assign the subscription to a variable so we can unsubscribe to prevent memory leaks
    this.sub = this.route.queryParams.subscribe((params: Params) => {
      this.var1 = params['var1'];
      this.var2 = params['var2'];
    });

    console.log(this.var1, this.var2);
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
  }
...
}
Sign up to request clarification or add additional context in comments.

Comments

-1

With regard to Angular 2 - How to pass URL parameters? the provided solution did not work for my origin issue, but Angular Route guards is the right feature to have a look.

Via route guards you can intercept and capture route information in front of the component processing.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.