简体   繁体   English

如何将新值绑定到数组变量从一个组件到另一个组件以及第一个组件中的现有数据

[英]how to bind the new values to array variable from one component to another component along with existing data's in first component

i has two components comp1 & comp2 我有两个组件comp1和comp2

comp1 has one array variable . comp1有一个数组变量。 i created constructor in comp2 for comp1 to access comp1 functions it is workiing correctly and the values are binding in same array variable which i binds. 我在comp2中创建了构造函数,以便comp1访问comp1函数,它可以正常工作,并且值绑定在我绑定的同一数组变量中。

i need to bind the value from comp2 along with existing datas in the array variable in comp1 我需要将comp2中的值与comp1中数组变量中的现有数据绑定在一起

Array variable in comp1 has some values already. comp1中的数组变量已经有一些值。

but my problem is when i binding the value from comp2 for the same variable the values are maintaing seperately not with existing datas in that array variable 但是我的问题是当我将comp2的值绑定到相同的变量时,这些值是单独维护的,而不是该数组变量中的现有数据

how to bind the new values to comp1 variable along with existing datas 如何将新值与现有数据绑定到comp1变量

I think you may directly assign data into comp1 . 我认为您可以直接将数据分配到comp1 Like this. 像这样。

array1 = values;

Instead of that, do this way 而不是那样做

array1.push(values);

It will add values in existing array. 它将在现有数组中添加值。

And make sure you are passig data in correct way. 并确保您以正确的方式获取密码数据。

Child to Parent: Sharing Data via ViewChild 子女与父母:通过ViewChild共享数据

What you need is a Shared Service. 您需要的是共享服务。

1) create data.service.ts (simple service) 1)创建data.service.ts(简单服务)

2) in this service define variable as BehaviorSubject 2)在此服务中,将变量定义为BehaviorSubject

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

@Injectable()
export class DataService {

  private messageSource = new BehaviorSubject('default message');
  currentMessage = this.messageSource.asObservable();

  constructor() { }

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

}

3) add this service as provider in module that is common for two components (app.module.ts) 3)将此服务添加为两个组件(app.module.ts)通用的模块中的提供程序

4) now you can set sared service variable in components like 4)现在您可以在类似的组件中设置sared服务变量

this.service.changeMessage(newData);

and you can subsribe to currentMessage value to get value, like 您可以订阅currentMessage值以获取值,例如

 this.service.currentMessage.subscribe(serviceValue => this.componentMessage = serviceValue );

Variable value from service will be the same for all components. 服务的可变值对于所有组件都是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM