0
votes

I'm trying to get parameters from url in AppComponent in my angular application.

But when I use ActivatedRoute to get params it gives null. This is my router configuaration.

  {
    path: '',
    component: HomeComponent,
    canActivate: [AuthGuard]
  },
  {
    path: 'product/:product',
    component: HomeComponent,
    canActivate: [AuthGuard]
  }

This is what I tried in AppComponent to get the the result of params from url.

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

ngOnInit() {

this.route.params.subscribe(params => {
      console.log(params['product']); //jsut print the result in console
});

//or can use to get the result
//console.log(this.route.snapshot.params['product'];

}

this code only works inside particular components. So, Is there any suitable way to get the results. [Angular 6+]

2
where are you subscribing to route.params ? Is it inside any function? please provide complete codeSachin Gupta
@SachinGupta yes, I edited the codeLilanka
It should work, can you please create a stackblitz to reproduce the issue.Sachin Gupta
@SachinGupta This is stackblitz link with the issue: angular-9xa95q.stackblitz.io/product/seLilanka

2 Answers

0
votes

First, create a sharedService

import { Injectable } from '@angular/core';
import {  Subject  } from 'rxjs';


@Injectable()
export class SharedService {

  myData: Subject<any> = new Subject<any>();

  constructor() {}

  setData(data) {
    this.myData.next(data);
  }
}

Then from where you want to set the data use this method:

export class MyComponent implements OnInit {

    constructor(private sharedService: SharedService) { }

    ngOnInit() {
       this.sharedService.setData(data);
    }
}

Then in your appComponent:

export class AppComponent implements OnInit {

  constructor(private sharedService: SharedService) {
    this.sharedService.myData.subscribe((value) => {
     console.log(value) // Here you will get your complete data
    });
  }

}

0
votes

Got it now. The issue is because the AppComponent is always there and its params are not updated. If you subscribe the activatedRoute in HomeComponent, you can get the updated value. If the requirement is to get the value in the AppComponent, you can follow @Chirag's answer by subscribing in AppCOmponent and updating the value from HomeComponent. Check out the forked code here