簡體   English   中英

在 Angular 中的組件之間共享數據

[英]Share data between components In Angular

其他帖子沒有幫助我解決這個問題

我想通過兩個組件並使用服務共享從 HTTP 請求中檢索到的變量。

為此我意識到了這一點,但不幸的是,我的組件中沒有顯示數據(控制台中沒有錯誤),也沒有編譯。 共享數據服務.ts

@Injectable({
  providedIn: 'root'
})
export class SharedataService {

  private dataSourceMyContainers = new Subject<any>();

  constructor(private dataService: RestApiService) { 
    this.getContainers();
  }

  getContainers(): any{
    this.dataService.getAllContainers().subscribe((res)=>{
      this.dataSourceMyContainers = res;       
    });    
  }

  getList(){
    return this.dataSourceMyContainers.asObservable();
  }
  
  updateApprovalMessage(message: any) {
    this.dataSourceMyContainers.next(message)
  }
}

第一個服務,例如 status-card.component.ts

@Injectable({
  providedIn: 'root'
})
export class StatusCardComponent implements OnInit {
  runningContainer?: number = 0;
  pausedContainer?: number = 0;
  stoppedContainer?: number = 0;
  failedContainer?: number = 0;
  dataSourceMyContainers: any = [];

  constructor(private sharedataService: SharedataService, private notification: NotificationsService) { 
  }

  ngOnInit(): any{
// it enters here
    this.sharedataService.getList().subscribe((res)=>{
      this.dataSourceMyContainers = res; // but not enter here
      console.log("res"+ res); // nothing displayed
    });    
  }  

  btnCountStatus(): void {
    this.runningContainer = this.dataSourceMyContainers.filter((container: any) => container.status === 'RUNNING').length;
    this.pausedContainer = this.dataSourceMyContainers.filter((container: any) => container.status === 'PAUSED').length;
    this.stoppedContainer = this.dataSourceMyContainers.filter((container: any) => container.status === 'STOPPED').length;
    this.failedContainer = this.dataSourceMyContainers.filter((container: any) => container.status === 'FAILED').length;
  }
}

感謝幫助 !

您的代碼有兩個問題:

  1. 您需要 BehaviorSubject 而不是 Subject 因為您需要“重播”值:

    私有 dataSourceMyContainers = new BehaviorSubject();

  2. 您需要從 Http-Call 中“下一個”您的結果

    getContainers(): any{ this.dataService.getAllContainers().subscribe((res)=>{ this.dataSourceMyContainers.next(res);
    });
    }

暫無
暫無

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

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