Angular-监听存储变化并从一个服务组件向另一个组件发出一个值——仅在服务完成某些操作后

Angular-Listening to store changes & emit a value from a Service component to a different component - only after Service completes certain operations

这里我们必须 类 GetDataAsyncService 等待 存储中的更改(而不是执行代码块在它下面直到商店发生变化( this.getDataAsyncService.getAsyncData().subscribe((data)=>{ )})。当从 MainComponent 调用它时,它会得到 return of(propA); (来自 GetDataAsyncService) 在执行侦听器中的代码块之前 - 因为侦听器仍在等待存储中的更改。 我只想在执行该操作块时发出该可观察对象。

export class GetDataAsyncService {
     propA;
     constructor(private store: Store<AppState>)

     getData():Observable<any>{
       this.store.pipe(select(appState)).subscribe((val)=>{  
         // operation block
         // some operations
         // some more operations 
         this.propA = val.propA;
       })
       return of(propA); // this should be emitted with the latest value only when the block of code above executes - not before that
     }
    
    

}

export MainComponent implenents OnInit{
  propA: string = '';
  constructor(private getDataAsyncService: GetDataAsyncService){}

  ngOnInit(): void{
    this.getDataAsyncService.getAsyncData().subscribe((data)=>{
      this.propA = data.propA;
    })
  }
  // any operation involving propA
  // code ......
  
}

您可以通过从 getData 函数返回 Observable 本身并将其映射到所需的 prop 而不是 subscribe 来实现这一点,如下所示:

export class GetDataAsyncService {
  propA;
  constructor(private store: Store<AppState>) {}

  getData(): Observable<any> {
    return this.store.pipe(
      select(appState),
      map((val) => val.propA)
    );
  }
}

export class MainComponent implements OnInit {
  propA: string = '';
  constructor(private getDataAsyncService: GetDataAsyncService) {}

  ngOnInit(): void {
    this.getDataAsyncService.getAsyncData().subscribe((propA) => {
      this.propA = propA;
    });
  }
}