简体   繁体   English

在角度 7 中的两个同级组件之间传递数据

[英]passing data between two sibling components in angular 7

Here the requirement is i need to display the user who logged in, in a home, for that i have a logincomponent , homecomponent and for data transfer i am using a service called dataService.ts,for me the data is coming up to dataService.ts but it is not coming to homecomponent这里的要求是我需要显示登录的用户,在家里,因为我有一个 logincomponent ,homecomponent 和数据传输我使用名为 dataService.ts 的服务,对我来说数据正在进入 dataService。 ts 但它没有进入 homecomponent

My code我的代码

imported dataservice in loginComponent在 loginComponent 中导入数据服务

this.userName consists of username who logged in this.userName 由登录的用户名组成

login component:登录组件:

this.ds.sendMessage(this.userName);

dataService:数据服务:

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

@Injectable({
    providedIn: 'root'
})
export class DataService
{
    constructor()
    {
    }

    private apiData = new Subject<Object>();
    public apiData$ = this.apiData.asObservable();

    sendMessage(message: Object)
    {
        this.apiData.next(message);
        console.log(message);
    }
}

homecoponent:家庭组件:

ngOnInit();
{
    console.log('in homecomponent');
    this.DataService.apiData$
        .subscribe(
            message =>
            {
                console.log(message);
            }
        );
}

Can anybody help?有人可以帮忙吗?

It is likely, that both DataServices are not the same.很可能,这两个 DataService 并不相同。 Please make sure you provide the service on a higher level (Module, not Component) or use a store both services are referring to.请确保您在更高级别(模块,而不是组件)上提供服务或使用两个服务所指的商店。

Create a data service that is responsible for broadcasting the value you pass:创建一个数据服务,负责广播你传递的值:

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

@Injectable({
  providedIn: 'root'
})
export class DataService {

  private value: string;
  listeners = [];

  constructor() {
    this.value = '';
  }

  onDataChange(fn) {
    this.listeners.push(fn);
  }

  set setData(value: string) {
    this.value = value;
    this.listeners.forEach((fn) => {
      fn(value);
    });
  }
}

In each of your component where you want to perform communication, inject the data service.在要执行通信的每个组件中,注入数据服务。

constructor(private dataService: DataService) {}

You can set the value of the data in a component like so:您可以像这样在组件中设置数据的值:

this.dataService.setData= 'New value';

You can then subscribe to the value change event of the data service in a different component on ngOnInit :然后,您可以在ngOnInit上的不同组件中ngOnInit数据服务的值更改事件:

ngOnInit() {
    this.dataService.onDataChange((value) => {
         this.data = value;
    });
}

Live Demo现场演示

嗨,您可以在这篇文章中查看这个基于fire-base 的帖子,作者提供了有关在任何类型(兄弟姐妹 - 兄弟姐妹,父 - 子,子 - 子...)的组件之间传递数据的一些解释

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

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