使用主题和代理传递数据 [英] Passing Data with Subjects and Proxies

查看:39
本文介绍了使用主题和代理传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在服务中使用主题来实现双向数据流?例如,假设我希望某个组件检索信息,然后通过服务 Subject 将其发布以供其他组件使用.

Is it possible to have a 2 way data flow using Subjects in a service? Suppose for example that I want some component to retrieve information and then post it through the service Subject for other another component to consume.

消费组件然后对该信息进行一些更改,然后重新发布它,以便原始组件可以检索更改.

The consuming component then makes some changes to this information and then re-posts it so that the original component can retrieve changes.

这可以使用观察者模式吗?

Is this possible using the Observer pattern?

此外,如果我想查看这些数据的变化(假设数据是通过数组传入的),我是否必须使用 proxy 来完成这个?

Also, if I wanted to watch this data for changes (let's say that the data came in through an array), would I have to use a proxy to accomplish this?

推荐答案

在组件之间传递数据时,我发现 RxJS BehaviorSubject 非常有用.

When passing data between components, I find the RxJS BehaviorSubject very useful.

您也可以使用常规的 RxJS Subject 通过服务共享数据,但这就是我更喜欢 BehaviorSubject 的原因.

You can also use a regular RxJS Subject for sharing data via a service, but here’s why I prefer a BehaviorSubject.

  1. 它将始终返回订阅的当前值 - 无需调用 onNext().
  2. 它有一个 getValue() 函数来提取最后一个值作为原始数据.
  3. 它确保组件始终接收最新的数据.
  4. 您可以使用 asObservable() 从行为主体中获取可观察对象行为主体的方法.
  5. 更多信息请参考此
  1. It will always return the current value on subscription - there is no need to call onNext().
  2. It has a getValue() function to extract the last value as raw data.
  3. It ensures that the component always receives the most recent data.
  4. you can get an observable from behavior subject using the asObservable() method on behavior subject.
  5. Refer this for more

示例

在服务中,我们将创建一个私有的 BehaviorSubject 来保存消息的当前值.我们定义了一个 currentMessage 变量来处理这个数据流作为一个被其他组件使用的可观察对象.最后,我们创建了调用 BehaviorSubject 的 next 函数来改变它的值.

In a service, we will create a private BehaviorSubject that will hold the current value of the message. We define a currentMessage variable to handle this data stream as an observable that will be used by other components. Lastly, we create the function that calls next on the BehaviorSubject to change its value.

父组件、子组件和兄弟组件都接受相同的处理.我们在组件中注入 DataService,然后订阅 currentMessage observable 并将其值设置为等于 message 变量.

The parent, child, and sibling components all receive the same treatment. We inject the DataService in the components, then subscribe to the currentMessage observable and set its value equal to the message variable.

现在,如果我们在这些组件中的任何一个中创建一个函数来更改消息的值.更新后的值会自动广播到所有其他组件.

Now if we create a function in any one of these components that changes the value of the message. The updated value is automatically broadcasted to all other components.

shared.service.ts

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

@Injectable()
export class SharedService {

  private messageSource = new BehaviorSubject<string>("default message");
  currentMessage = this.messageSource.asObservable();

  constructor() { }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

}

parent.component.ts

import { Component, OnInit } from '@angular/core';
import { DataService } from "../data.service";

@Component({
  selector: 'app-parent',
  template: `
     {{message}}
   `,
   styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {

  message: string;

  constructor(private data: DataService) { }

  ngOnInit() {
    this.data.currentMessage.subscribe(message => this.message = message)
  }
}

sibling.component.ts

import { Component, OnInit } from '@angular/core';
import { SharedService } from "../shared.service";

@Component({
  selector: 'app-sibling',
  template: `
    {{message}}
    <button (click)="newMessage()">New Message</button>
  `,
  styleUrls: ['./sibling.component.css']
})
export class SiblingComponent implements OnInit {

  message: string;

  constructor(private service: SharedService) { }

  ngOnInit() {
  }

  newMessage() {
    this.service.changeMessage("Hello from Sibling");
  }

}

这篇关于使用主题和代理传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆