javascript - 将数据从服务推送到组件的最佳方式是什么?

标签 javascript html angular service observable

在我的 Angular 项目中,我目前有一个服务,它使用 http 调用从我的 java 代码中检索数据。该服务每 10 秒调用一次 Java 端并从中获取新数据。我现在有另一个组件需要我的服务中的数据。我需要这个组件有一个名为“数据”的字段,当服务获取新信息时,该字段会自动更新。

如何设置它们以便服务将新信息推送到我的其他组件?我希望能够在组件的 html 中使用 {{data}} 并自动更新,而无需重新加载页面。

我的组件已经有“Autowired”服务。因此,目前我可以只调用“this.data = this.service.getData()”,但该调用是在我的 ngOnInit 方法中,因此它只发生一次,并且当服务的数据字段更新时,数据字段不会更新。

最佳答案

您可以创建一个消息服务来为订阅者发布数据,或者在您的原始服务中实现此功能。

我建议有一个单独的消息传递服务,并让相关组件或服务发布/订阅它。

消息传递.service.ts

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';


@Injectable()
export class MessagingService {
  private sharedValue = new Subject<string>();  

  // Observable string streams
  sharedValue$ = this.sharedValue.asObservable();

    // Service message commands
  publishData(data: string) {
    this.sharedValue.next(data);
  }

您可以像这样注入(inject)服务:

constructor(private messagingService: MessagingService ) {}

发布到服务:

this.messagingService.publishData(sharedValue);

订阅服务:

this.messagingService.sharedValue$.subscribe(
            data => {                    
                this.localSharedValue = data;
            });

来自以下答案:DeborahK(每个人都应该观看的 Pluralsight 类(class))

Actually, all you need is a getter.

Change your 'data' property to a getter and that will do the trick:

get data(): any {
    return this.service.getData();
}

Angular change detection will detect any time that data is changed in the service which will cause it to re-evaluate its bindings and call this getter to re-get the data.

No need for a fancy service or Subject. :-)

关于javascript - 将数据从服务推送到组件的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48386831/

相关文章:

javascript - 闭包中的变量存储在哪里 - 堆栈还是堆?

javascript - jquery - 折叠/扩展 div?

javascript - jQuery.Deferred 异常 : $(. ..).noUiSlider 不是函数

Java 加载网页并跟踪 HTML 中的更改

html - 使 flex 元素换行以形成 2 列网格

javascript - 带有 2 个 if 和 else 条件的 ng-style

angular - 由于未设置 APP_BASE_HREF,在 Angular 6 中测试失败

javascript - 正则表达式匹配包含除某些字符串之外的某些字符串的模式

html - 带有水平子菜单的 CSS 下拉菜单

angular - 从 api 响应创建可观察数组