猿问

我如何在角度中找到先前路线的参数

我想在 angular typescript 中找到先前路线中的参数。


我使用此代码:


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;

        }

    });

}

但我无法访问此网址的参数:


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

我想要 ti 访问200。我怎样才能在 url 中找到参数????


慕婉清6462132
浏览 127回答 3
3回答

慕少森

您可以在组件文件中执行此操作,但最佳实践是在服务中执行此操作(使用 rxjs)以传递数据并在组件文件中调用它为您服务export class myService  {     constructor() { }   private param = new BehaviorSubject("");  sharedParam = this.param.asObservable();  paramToPass(param:string) {     this.param.next(param)}    }在设置参数的组件类中export class ComponentSetParam  { param: string       constructor(private myService: Service)   this.myService.setParam(this.param);}在你的appModule@NgModule({  declarations: [YourComponents]  imports: [ AppRoutingModule, YourModules...],  providers: [ShareService],})export class AppModule {}要传递数据的组件export class ComponentGetParam  {    paramFromService: string         constructor(private myService: Service) {       this.shareService.sharedData.subscribe(data : string => {          this.paramFromService = data;     })   }  }

红颜莎娜

演示您可以在服务中进行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)}    }在构造函数中constructor(private shareService: ShareService)在组件中ngOnDestroy设置这样的 this.shareService.setParam(param);在应用模块中  providers:[ShareService ]在 ngOnInit 或构造函数中的新组件中得到类似 this.shareService.sharedData.subscribe(data=> { console.log(data); }) 

料青山看我应如是

尝试这个:readonly _destroy$: ReplaySubject<boolean> = new ReplaySubject<boolean>(1);constructor(&nbsp; &nbsp; private activatedRoute: ActivatedRoute,) {&nbsp; this.activatedRoute.parent.paramMap&nbsp; &nbsp; &nbsp; .pipe(&nbsp; &nbsp; &nbsp; &nbsp; distinctUntilChanged(),&nbsp; &nbsp; &nbsp; &nbsp; takeUntil(this._destroy$)&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; .subscribe((params: ParamMap) => {&nbsp; &nbsp; &nbsp; &nbsp; const id = params.get('id');&nbsp; &nbsp; });}ngOnDestroy() {&nbsp; this._destroy$.next(true);&nbsp; this._destroy$.complete();}其中“id”是您在路由中使用的名称,例如path: '/claims-manager/:id/'
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答