Совместное использование данных между компонентами в Angular

#angular #components

#angular #Компоненты

Вопрос:

Другие сообщения не помогают мне решить эту проблему

Я хочу поделиться переменной, полученной из HTTP-запроса, через два компонента и с помощью сервиса.

Для этого я понял это, но, к сожалению, данные не отображаются ни в моих компонентах (нет ошибки в консоли), ни в компиляции. sharedata.service.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

2. @enno.void Спасибо, только что протестировано, но не работает слишком общедоступный dataSourceMyContainers = new BehaviorSubject<any>(null);

3. существует еще одна проблема: this.dataSourceMyContainers = res; -> this.dataSourceMyContainers.next(res);

4. Большое спасибо! Поместите это в ответ, я проверю

Ответ №1:

В вашем коде есть две проблемы:

  1. Вам нужен BehaviorSubject вместо Subject, потому что вам нужно «воспроизведенное» значение:

    private dataSourceMyContainers = new BehaviorSubject();

  2. Вам нужно «далее» ваши результаты формируют Http-вызов

    getContainers(): любой{ this.DataService.getAllContainers().subscribe((res)=>{ this.dataSourceMyContainers.next(res);
    });
    }