数据从 AppComponent 传递到另一个在不同时间加载的组件

Data passing from AppComponent to another component which loads at a different time

我想在 AppComponent 中调用一个服务来获取一些数据,然后我想将它发送到另一个在另一个时间加载的组件。如何确保可以在其他组件中捕获数据?我希望此设置最大限度地减少 API 调用,因为我们从 api 获取的相同数据在 2-3 个地方重复使用。

您可以在服务中使用 BehaviorSubject。 当稍后加载的组件注入服务并订阅 BehaviorSubject 时,它将立即获得最后发出的值。

您想将数据存储在全局可注入服务中。在此服务中,您应该定义一个 BehaviorSubject。见下文。

@Injectable()
export class DataService {

  // Can subscribe to and emit events from a BehaviorSubject
  // BehaviorSubject can act like an event bus but will also return the last value in the stream upon subscription
  public userSubject = new BehaviorSubject(null);

}