我有兩個不同的組件
first.component.ts
ngOnInit(): void {
}
setStatusOfUser(){
this.Service.setStatus(Id,userId).subscribe((data)=>{
this.msg=data;
})
}
第二個組件.ts
ngOnInit():void {
this.getProgress()
}
getProgress(){
this.service1.getProgress().subscribe(data=>{
this.progresss=data;
});
}
當我重繪 頁面時它的作業但是當單擊 setStatusofUser 我想在另一個組件中呈現獲取進度方法時如何做到這一點。
uj5u.com熱心網友回復:
first.component.ts
您可以使用 ViewChild Annotation 呼叫另一個組件中的方法
@ViewChild(SecondComponent) secondComponent!: SecondComponent;
setStatusOfUser(){
this.secondComponent.getProgress();
}
uj5u.com熱心網友回復:
它僅在重繪 時起作用的原因是您getProgress()只呼叫一次onInit()。您可以使用的一種可能的解決方案是使用服務在組件之間共享資訊。
服務
private statusObs = new BehaviorSubject<any>(null);
setStatus(data: any) {
this.statusObs.next(data);
}
getStatus() {
return this.statusObs;
}
第一個組件
constructor(private communicationService:<YourServiceName>){}
ngOnInit(): void {
}
setStatusOfUser(){
this.Service.setStatus(Id,userId).subscribe((data)=>{
this.communicationService.setStatus(data); // Pass data to the service
this.msg=data;
});
}
第二部分
constructor(private communicationService:<YourServiceName>){}
ngOnInit():void {
this.communicationService.getStatus().subscribe( status => {
// We used BehaviorSubject<any>(null) with initial value null
// so use this null check to avoid calling getProcess() in the beggining
if (status !== null) { // check if your data is the data you want
this.getProgress();
}
});
}
getProgress(){
this.service1.getProgress().subscribe(data=>{
this.progresss=data;
});
}
uj5u.com熱心網友回復:
在你的第二個組件中......
readonly progress$: Service1['getProgress'];
constructor(
readonly communicationService: CommunicationService,
readonly service1: Service1
) {
this.progress$ = this.communicationService.getStatus().pipe(
filter(status => status !== null),
switchMap(() => this.service1.getProgress()), // ignore whatever the status is, just get the new progress.
);
}
這將創建一個可觀察物件,每次從getStatus發出的可觀察物件時,都會呼叫this.service1.getProgress()并發出任何可觀察物件回傳的內容......直到并且除非getStatus再次發出回傳的可觀察物件。
然后,在您的第二個組件的模板中,顯示它:
<div>{{progress$ | asynch}}</div>
這將自動訂閱,在發出時更新網頁progress$,并在組件關閉時取消訂閱。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/419754.html
標籤:
上一篇:typecastreacttypescript組件類道具
下一篇:不良的相機校準會影響像素坐標嗎?
