我想用角度打字稿找到上一条路线中的参数。
我使用此代码:
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;
}
});
}
但是我无法访问该URL的参数:
http://localhost:4200/claims-manager/200/edit
我要ti访问200
。如何在url中找到参数????
答案 0 :(得分:1)
您可以在组件文件中进行操作,但是最好的做法是在服务中(使用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;
})
}
}
答案 1 :(得分:0)
尝试一下:
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();
}
其中“ id”是您在路由中使用的名称,例如
path: '/claims-manager/:id/'
答案 2 :(得分:0)
Demo您可以在服务中完成
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); })