首页 > 解决方案 > Angular 中的主题

问题描述

因此,假设您有一个带有以下组件和服务文件的 Angular 应用程序。在组件中,用户在服务文件中订阅此主题。

现在假设有人在服务文件中发出服务器请求并从服务器获取响应。

当我们收到服务器响应并使用 next() 方法触发 Subject 时,我们是否只会收到订阅此 Subject 的组件中的数据,或者基本上是当前正在使用此应用程序并在其组件中打开此订阅的每个人?

零件

export class exampleComponent implements OnInit {
  ngOnInit() {
    this.exampleService.exampleSubject().subscribe();
  }
}

服务

export class exampleService {
  exampleSubject = new Subject();

  someOtherMethodWithHttpRequest() {
    return this.http.get(url).pipe(map(data => this.exampleSubject.next()));
  }
}

标签: angular

解决方案


它将因为它是一个主题,并且主题是多播的。

编辑:我最初的回答是否定的,因为只有 BehaviorSubject 和 ReplaySubject 是 multicast。这是错误的,所有主题都是多播的。

不过,在这种情况下使用 BehaviorSubject 是一个好主意:它保证每个订阅者都将收到来自 api 调用的值,即使他们在 api 调用发生后订阅。如果您在 Subject 发出它的值后订阅它,您将永远不会从该 api 调用中收到该值。


推荐阅读