3 回答
TA贡献2019条经验 获得超9个赞
您可以在组件文件中执行此操作,但最佳实践是在服务中执行此操作(使用 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;
})
}
}
TA贡献1842条经验 获得超12个赞
演示您可以在服务中进行
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); })
TA贡献1772条经验 获得超8个赞
尝试这个:
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/'
添加回答
举报