0

i want find the params in previous route in angular typescript .

i use this code :

private previousUrl: string = undefined;
private currentUrl: string = undefined;

constructor(private router: Router) {
    this.currentUrl = this.router.url;
    router.events.subscribe(event => {
        if (event instanceof NavigationEnd) {
            this.previousUrl = event.url;
            this.currentUrl =  this.currentUrl;
        }
    });
}

but i can not access to the params of this url :

http://localhost:4200/claims-manager/200/edit

i want ti access 200 . how can i find params in url ????

kianoush dortaj
  • 411
  • 7
  • 24

3 Answers3

1

You can do it in your component file but It is a best practice to do it in a service (using rxjs) to pass data and call it in your component file

In your service

export class myService  {   
  constructor() { } 
  private param = new BehaviorSubject("");
  sharedParam = this.param.asObservable();


  paramToPass(param:string) { 
    this.param.next(param)}    
}

In your component class that set param

export class ComponentSetParam  {
 param: string   
    constructor(private myService: Service)
  
 this.myService.setParam(this.param);

}

in your appModule

@NgModule({
  declarations: [YourComponents]
  imports: [ AppRoutingModule, YourModules...],
  providers: [ShareService],
})
export class AppModule {}

Component that you want to pass data

export class ComponentGetParam  {
    paramFromService: string
    
     constructor(private myService: Service) {
       this.shareService.sharedData.subscribe(data : string => { 
         this.paramFromService = data;
     })
   }
  

}

 
Chris
  • 806
  • 1
  • 10
  • 17
0

Try this:

readonly _destroy$: ReplaySubject<boolean> = new ReplaySubject<boolean>(1);

constructor(
    private activatedRoute: ActivatedRoute,
) {
  this.activatedRoute.parent.paramMap
      .pipe(
        distinctUntilChanged(),
        takeUntil(this._destroy$)
        )
      .subscribe((params: ParamMap) => {
        const id = params.get('id');
    });
}

ngOnDestroy() {
  this._destroy$.next(true);
  this._destroy$.complete();
}

Where 'id' is a name, that you use in the routing, e.g.

path: '/claims-manager/:id/'
0

Demo You can do it in service

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class ShareService  {   
  constructor() { } 
  private paramSource = new BehaviorSubject("");
  sharedData = this.paramSource.asObservable();
  setParam(param:string) { this.paramSource.next(param)}    
}

in constructors

constructor(private shareService: ShareService)

in component in ngOnDestroy set this like this.shareService.setParam(param);

in appmodule

  providers:[ShareService ]

in new component in ngOnInit or in constructor get like

 this.shareService.sharedData.subscribe(data=> { console.log(data); }) 
mr. pc_coder
  • 16,412
  • 3
  • 32
  • 54