Angular 4 pass data between 2 not related components

前端 未结 5 1529
栀梦
栀梦 2020-11-27 13:47

I have a questions about passing data in Angular.

First, I don\'t have a structure as

5条回答
  •  情深已故
    2020-11-27 14:21

    This is a case where you want to use a shared service, as your components are structured as siblings and grandchildren. Here's an example from a video I created a video about sharing data between components that solves this exact problem.

    Start by creating a BehaviorSubject in the service

    import { Injectable } from '@angular/core';
    import { BehaviorSubject } from 'rxjs/BehaviorSubject';
    @Injectable()
    export class DataService {
    
      private messageSource = new BehaviorSubject("default message");
      currentMessage = this.messageSource.asObservable();
    
      constructor() { }
    
      changeMessage(message: string) {
        this.messageSource.next(message)
      }
    
    }
    

    Then inject this service into each component and subscribe to the observable.

    import { Component, OnInit } from '@angular/core';
    import { DataService } from "../data.service";
    @Component({
      selector: 'app-parent',
      template: `
        {{message}}
      `,
      styleUrls: ['./sibling.component.css']
    })
    export class ParentComponent implements OnInit {
    
      message:string;
    
      constructor(private data: DataService) { }
    
      ngOnInit() {
        this.data.currentMessage.subscribe(message => this.message = message)
      }
    
    }
    

    You can change the value from either component and the value will be updated, even if you don't have the parent/child relationship.

    import { Component, OnInit } from '@angular/core';
    import { DataService } from "../data.service";
    @Component({
      selector: 'app-sibling',
      template: `
        {{message}}
        
      `,
      styleUrls: ['./sibling.component.css']
    })
    export class SiblingComponent implements OnInit {
    
      message:string;
    
      constructor(private data: DataService) { }
    
      ngOnInit() {
        this.data.currentMessage.subscribe(message => this.message = message)
      }
    
      newMessage() {
        this.data.changeMessage("Hello from Sibling")
      }
    
    }
    

提交回复
热议问题