Angular router gets child parameter from root component

I have this structure in mine app.component.html:

<app-main-nav></app-main-nav>
<router-outlet></router-outlet>

These are my routes:

const routes = [
  {path: "", redirectTo: "home", pathMatch: "full"},
  {
    path: "posts", component: PostsComponent, 
    children: [{
      path: ":id",
      component: PostComponent
    }];
  }
]

I'm trying to access options on page PostComponentin MaiNavComponent, but this causes an error.

export class MainNavComponent implements OnInit {

  constructor( private route: ActivatedRoute) {
    route.params.subscribe(console.log)
  }
}

How can I get :idout PostComponentof MainNavComponent?

I tried to do this:

 route.params.subscribe(console.log)

Here I get an empty object.

And this:

 route.firstChild.params.subscribe(console.log)

Unable to read params properties from null

+4
source share
3 answers

, ActivatedRoute , (route-outlet). :

export class MainNavComponent implements OnInit {

    constructor(private router: Router) {}

    ngOnInit() {

        // Fires when the url changes
        this.router.events.subscribe(data => {
            // Only handle final active route
            if (data instanceof NavigationEnd) {

                 // parsedUrl conatins params, queryParams 
                 // and fragments for the active route
                 let parsedUrl = this.router.parseUrl(this.router.url);

                 console.log(parsedUrl);
            }
        });
    }
}

, .

+1
constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute) {
}

ngOnInit() {
  this.loadParams();
}

private loadParams(): void {
    this.router.events.subscribe(event => {
        if (event instanceof NavigationEnd) {
            let activatedRoute = this.activatedRoute.firstChild;
            while (!activatedRoute) {
                activatedRoute = activatedRoute.firstChild;
            }

            const value = activatedRoute.snapshot.paramMap.get('parmeter key');
        }
    });
}
0

You need to take a snapshot to get the id from the URL. Create a constructor below

constructor( private route: ActivatedRoute) {   
  }
ngOnInit() {
  // (+) converts string 'id' to a number
  let id = +this.route.snapshot.params['id'];


}
-1
source

Source: https://habr.com/ru/post/1674225/


All Articles