简体   繁体   English

如何在组件之间正确传输数据? Angular

[英]How to properly transfer data between components? Angular

I need your help.我需要你的帮助。 I am practicing passing data between components.我正在练习在组件之间传递数据。 I am trying to transfer data between components using simple arrays and subjects.我正在尝试使用简单的 arrays 和主题在组件之间传输数据。 Unfortunately, I get an error when I want to add an element using the subject method.不幸的是,当我想使用主题方法添加元素时出现错误。 The error looks like this: Error trying to diff 'hello'. Only arrays and iterables are allowed错误如下所示: Error trying to diff 'hello'. Only arrays and iterables are allowed Error trying to diff 'hello'. Only arrays and iterables are allowed

I have only 2 questions:我只有两个问题:

  1. What is my mistake, what did I do wrong?我的错误是什么,我做错了什么?
  2. What is the best way to transfer data between components: to use services with simple arrays or to use subject or to use Input Output + EventEmmiter decorators?在组件之间传输数据的最佳方式是什么:使用带有简单 arrays 的服务或使用主题或使用 Input Output + EventEmmiter 装饰器?

Thank you very much非常感谢

DataTransferService数据传输服务

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

@Injectable({
   providedIn: 'root'
})

export class DataTransferService {
   public array: any[] = [];
   public transferArray = new BehaviorSubject<any>([]);
}

ComponentOne组件一

import {Component} from "@angular/core";
import {DataTransferService} from "../data-transfer.service";

@Component({
   selector: 'component-one',
   template: `<h1>component one</h1>
           <button (click)="sendData()">Send data array</button>
           <button (click)="sendDataTwo()">Send data subject</button`
})

export class ComponentOne {

constructor(public dataService: DataTransferService) {}

   sendData() {
      this.dataService.array.push(`hello` + 1)
   }

   sendDataTwo() {
      this.dataService.transferArray.next('hello');
   }

}

ComponentTwo组件二

import {Component} from "@angular/core";
import {DataTransferService} from "../data-transfer.service";

@Component({
   selector: 'component-two',
   tepmlate: `<h1>component two</h1>
             <div>using array<div *ngFor="let element of elements">{{element}}</div></div>
             <div>using subject<div *ngFor="let subj of subjectElements">{{subj}}</div></div>`

export class ComponentTwo {
   public elements: any;
   public subjectElements: any;

   constructor(public dataService: DataTransferService) {
      this.elements = this.dataService.array;
      this.dataService.transferArray.subscribe(value => {
        this.subjectElements = value;
      })
    }
   }
}
  1. What is my mistake, what did I do wrong?我的错误是什么,我做错了什么?

Ans: You need to push data into the array and then call the next method of the behaviour subject. Ans:你需要将数据压入数组,然后调用行为主体的next方法。 Only then data will be pushed.只有这样,数据才会被推送。 Also either maintain an array with a subject, or a behaviour subject that stores an array.也要么维护一个带有主题的数组,要么维护一个存储数组的行为主题。 In the below example, I am using a behaviour subject that stores an array!在下面的示例中,我使用了一个存储数组的行为主题!

  1. What is the best way to transfer data between components: to use services with simple arrays or to use subject or to use Input Output + EventEmmiter decorators?在组件之间传输数据的最佳方式是什么:使用带有简单 arrays 的服务或使用主题或使用 Input Output + EventEmmiter 装饰器?

Simple parent child communication (child is inside parent) -> @Input @Output简单的父子通信(子在父内部)-> @Input @Output

Simple parent child communication but child shown inside parent using routing -> subject emitter pattern or share the values through a common service.简单的父子通信,但子节点显示在父节点内部,使用路由 -> 主题发射器模式或通过公共服务共享值。

parent to distant child and vice versa, lots of components inbetween -> subject emitter pattern or share the values through a common service.父母到遥远的孩子,反之亦然,中间有很多组件 -> 主题发射器模式或通过公共服务共享值。


Change the code as below更改代码如下

DataTransferService数据传输服务

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

@Injectable({
   providedIn: 'root'
})

export class DataTransferService {
   public elementsArray = [];
   public transferArray = new BehaviorSubject<any>([]);
   public elementsArraySubject = new BehaviorSubject<any>([]);

   addNewData(data: any) {
       const arr = this.transferArray.getValue();
       arr.push(data);
       this.transferArray.next(data);
   }
}

ComponentOne组件一

import {Component} from "@angular/core";
import {DataTransferService} from "../data-transfer.service";

@Component({
   selector: 'component-one',
   template: `<h1>component one</h1>
           <button (click)="sendData()">Send data array</button>
           <button (click)="sendDataTwo()">Send data subject</button`
})

export class ComponentOne {

constructor(public dataService: DataTransferService) {}

   sendData() {
      this.dataService.addNewData(`hello` + 1);
   }

   sendDataTwo() {
      this.dataService.elementsArray.push('hello');
      this.dataService.elementsArraySubject.next();
   }

}

ComponentTwo组件二

import {Component} from "@angular/core";
import {DataTransferService} from "../data-transfer.service";

@Component({
   selector: 'component-two',
   tepmlate: `<h1>component two</h1>
             <div>using array<div *ngFor="let element of elements">{{element}}</div></div>
             <div>using subject<div *ngFor="let subj of subjectElements ">{{subj}}</div></div>`

export class ComponentTwo {
   public elements: any;
   public subjectElements: any;

   constructor(public dataService: DataTransferService) {
      this.dataService.transferArray.subscribe(value => {
        this.subjectElements = value;
      })
      this.dataService.elementsArraySubject.subscribe(() => {
        this.elements = this.dataService.elementsArray;
      })
    }
   }
}

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

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