Angular 在角坐标系中的组件之间共享数据

Angular 在角坐标系中的组件之间共享数据,angular,components,Angular,Components,其他帖子没有帮助我解决这个问题 我想通过两个组件和一个服务共享从HTTP请求检索到的变量 为此,我意识到了这一点,但不幸的是,数据没有显示在我的组件(控制台中没有错误)或编译中。 sharedata.service.ts @Injectable({ providedIn: 'root' }) export class SharedataService { private dataSourceMyContainers = new Subject<any>(); cons

其他帖子没有帮助我解决这个问题

我想通过两个组件和一个服务共享从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)
  }
}


谢谢你的帮助

您的代码有两个问题:

  • 您需要行为主体而不是主体,因为您需要“重播”值:

    private dataSourceMyContainers=新行为主体()

  • 您需要从Http调用中“下一步”查看结果

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


  • 更改以BehaviorSubject@enno.void谢谢,刚刚测试过,但不太适用于公共数据源mycontainers=newbehaviorsubject(null);还有另一个问题:this.dataSourceMyContainers=res;->this.dataSourceMyContainers.next(res);谢谢!把它放在回答中,我会验证
    @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;
      }
    }