How to access variables of one component in another component [Angular]

后端 未结 2 1739
渐次进展
渐次进展 2021-01-29 07:59

I\'m new to Angular. I\'m trying a simple thing today. I\'ve gone through many answers but not able implement them correctly. I want to access some variables of filter-pan

2条回答
  •  说谎
    说谎 (楼主)
    2021-01-29 08:24

    If both component don't have parent child relationship and if you want to pass the data between them then you can implement the RxJS subject for the same. I hope it helps you out

    Message Service

    import { Injectable } from '@angular/core';
    import { Observable, Subject } from 'rxjs';
    
    @Injectable({ providedIn: 'root' })
    export class MessageService {
        private subject = new Subject();
    
        sendMessage(message: string) {
            this.subject.next({ text: message });
        }
    
        clearMessages() {
            this.subject.next();
        }
    
        getMessage(): Observable {
            return this.subject.asObservable();
        }
    }
    

    filter-panel.component.ts

    import { Component, OnInit } from '@angular/core';
    import { messageService } from '../MesssageService.ts'
    @Component({
        ...
    })
    export class FilterPanelComponent implements OnInit {
    
    public activeFilters: string[];
    public text: string="hello world";
    
    constructor(private messageService: MessageService) {
        this.activeFilters = [
            'Apple',
            'Grapes',
            'Bana'
        ];
     }
    
    ngOnInit() {}
         this.messageService.sendMessage('data from filterPanelComponent'); // here you can also pass the object 
    }
    

    filter-bar.component.ts

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { messageService } from '../MesssageService.ts'
    
    @Component({
        ...
    })
    export class FilterBarComponent implements OnInit {
    
        constructor(private messageService: MessageService) {
    
        }
    
        ngOnInit() {
         this.messageService.getMessage().subscribe(response => {
         // here we get the data from another component
          console.log(response);
         })
        }
    }
    
    

提交回复
热议问题