簡體   English   中英

如何以角度從一個組件調用另一個組件的方法

[英]How to call a method from one component to another in angular

我有一個看起來像這樣的組件:

export class JobStatusComponent extends BaseTableView implements OnInit, OnDestroy {
 
 public getJobstatusdata(host) {
    this.apiService.getjobstatusdata(host).subscribe((data: any) => {
      this.jobList = data.JobList.ScheduleJobList.ScheduleJob;
      this.jobList.forEach((val) => {
        val.JobType = val.XMLQuery.Query.JobType;
        const { Password, FingerPrint, ...newObject } = val.XMLQuery.Query;
        val.QueryString = JSON.stringify(newObject)
      })

      this.setTableData(this.jobList);
      this.isDataLoaded = true;
    });
  }

}

單擊選項卡時,我想在另一個組件中調用此方法。 下面的函數在選項卡的父組件中被調用,這就是我希望函數調用發生的地方:

 updateactiveTab(activeTab: string) {
    console.log('activetab', activeTab)
    this.activetab = activeTab;
    if(this.activetab === 'Job Status') {
      console.log('I am in Job Status tab');
     //Call the method here
    }

  }

我嘗試導入組件並使用其功能如下所示,但它給出了錯誤:

import { JobStatusComponent } from '../job-status/job-status.component';

export class TraceLogpageComponent implements OnInit {

  activetab;
   
  tabfocusarr = ['Service Logs', 'System Logs', 'Job Status']
  tabfocus = 0;
  constructor(private modal: ModalService) {

  }

  ngOnInit() {
    let jobStatusComp =  JobStatusComponent;
    jobStatusComp.getJobstatusdata()
  }

  updateactiveTab(activeTab: string) {
    console.log('activetab', activeTab)
    this.activetab = activeTab;
    if(this.activetab === 'Job Status') {
      console.log('I am Job Status');
     //Call the method here
    }

  }

我收到此錯誤:

類型“typeof JobStatusComponent”上不存在屬性“getJobstatusdata”。

您可以使用 angular 服務來實現 getJobstatusdata() 方法。 然后根據需要在 TraceLogpageComponent 或 JobStatusComponent 的構造函數中傳遞新服務的實例。 當您需要刷新表數據時,您應該能夠獲取 setTableData 而無需一次又一次地實際調用 api 或將布爾參數傳遞給 getJobstatusdata() 。

來自另一個組件的方法的調用是一種氣味。 通常,這意味着@Input@Output設計稍有變化就可以了。 例如, getJobstatusdata(host)方法可能會被更改,這樣host將是一個@Input並且getJobstatusdata將在屬性@Input() host更改時調用。

無論如何,如果JobStatusComponent是兒童TraceLogpageComponent你可能會利用@ViewChild指令。 否則,我真的建議審查設計。 使用可觀察的共享服務或將getJobstatusdata移動到服務中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM