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條經驗 獲得超13個贊
演示您可以在服務中進行
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/'
添加回答
舉報