Angular 中没有输入的两种方式绑定 [英] Two way binding in Angular without Input

查看:43
本文介绍了Angular 中没有输入的两种方式绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类 ObjectComponent 来保存一些数据:

I have a class ObjectComponent which holds some data:

@Injectable()
export class ObjectComponent{
data: any;
....
...
}

我还有另一个组件 ObjectViewComponent:

And I have another Component ObjectViewComponent:

export class ObjectViewComponent{
    data: any;

constructor(
  @Inject(forwardRef(() => ProposalComponent)) public parentObject:ProposalComponent)
  {
    this.data=this.parentObject.data;
  }

如您所见,我想从父组件访问数据(因为它们是从另一台服务器加载的,我想避免 2 个 http 请求).由于 ObjectViewComponent 是使用路由器功能创建的,因此我无法使用 Input 将数据从父级传递到子级.

As you see I want to access the data from the parent component (since they are loaded from another server and I want to avoid 2 http request). Since the ObjectViewComponent is created using router functionality I cannot pass the data from parent to child using Input.

到目前为止一切正常,但 ObjectViewComponent 和 ObjectComponent 中的数据之间没有 2 向绑定.因此,每当我更改 ObjectViewComponent 中的数据时,它都不会更改 ObjectComponent 中的数据,反之亦然.任何想法如何实现两个组件之间的双向绑定?我对 Angular 不是很熟悉 - 我在服务等方面玩过一些,但在这个例子中我没有实现 2 向绑定.我还检查了 stackoverflow,没有一个例子对我有用.

This all works fine so far but there is no 2-way binding between the data in the ObjectViewComponent and the ObjectComponent. So whenever I change the data in ObjectViewComponent it will not change the data in ObjectComponent and vice versa. Any ideas how to achieve 2-way binding between both components? I am not very experience with Angular - I played a little bit with services etc. but I failed to achieve the 2-way binding in this example. I also checked stackoverflow none of the examples there worked for me.

谢谢,迈克尔

推荐答案

首先创建一个服务并在那里获取数据,比如在 service.ts 文件中,然后从该数据创建一个主题.

First create a service and fetch the data there, say in the service.ts file and create a Subject from that data.

    data:CustomClass;
    dataSubject = new BehaviorSubject(data);
    fetchData(){
      //////fetch the data
      setData(fetchedData)
    }

    setData(data){
      this.data = data;
      dataSubject.next(data)
    }

现在在你想得到通知的所有组件中,订阅主题为

Now in all the components where you want to get notified, subscribe the subject as

this.service.dataSubject.subscribe({
                next: (data) => {
                    /////this will be called 1. on first subscribe 2. on subsequent calls to setData() method in service;
                }
            })

希望对你有帮助

这篇关于Angular 中没有输入的两种方式绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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