简体   繁体   中英

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

My code

imported dataservice in loginComponent

this.userName consists of username who logged in

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. 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() {
    this.dataService.onDataChange((value) => {
         this.data = value;
    });
}

Live Demo

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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