angular - 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()));
}
}
解决方案
它将因为它是一个主题,并且主题是多播的。
编辑:我最初的回答是否定的,因为只有 BehaviorSubject 和 ReplaySubject 是 multicast。这是错误的,所有主题都是多播的。
不过,在这种情况下使用 BehaviorSubject 是一个好主意:它保证每个订阅者都将收到来自 api 调用的值,即使他们在 api 调用发生后订阅。如果您在 Subject 发出它的值后订阅它,您将永远不会从该 api 调用中收到该值。
推荐阅读
- sql - 用日期值替换字符串
- date - 从 Java 调用 oracle 数据库时,TO_DATE ('01/01/1980','dd/mm/yyyy') 不起作用
- amazon-web-services - 如何结合使用 AWS lambda 和 S3 来获取结果
- angular - jest.fn() 不涵盖模拟函数内部编写的代码行
- laravel - Laravel 验证请求过滤器字段,字段名称中带有点(句点)
- c# - 如何找到对 C# 9 记录定义的字段的所有引用?
- javascript - 我无法到达 id。在完整日历中删除事件,但未在数据库中删除
- r - shinyAppDir(x) 中的错误:应用程序目录必须包含 app.R 或 server.R
- python - 基于日期而不是行的移动平均值
- json - 如何使用 jq 从键名中删除引号并删除大括号?