Как получить доступ к переменным одного компонента в другом компоненте [Angular] - PullRequest
0 голосов
/ 06 марта 2020

Я новичок в Angular. Я пытаюсь сделать простую вещь сегодня. Я прошел через много ответов, но не смог правильно их реализовать. Я хочу получить доступ к некоторым переменным filter-panel в filter-bar, (мои два пользовательских компонента). Но ни один из них не является родителем-ребенком друг для друга. Они независимы, хотя и в одном каталоге. Здесь я создал stackblitz . А вот и мой код:

filter-panel.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
    ...
})
export class FilterPanelComponent implements OnInit {

public activeFilters: string[];
public text: string="hello world";

constructor() {
    this.activeFilters = [
        'Apple',
        'Grapes',
        'Bana'
    ];
}

ngOnInit() {}

}

filter-bar.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { FilterPanelComponent } from './filter-panel/filter-panel.component';

@Component({
    ...
})
export class FilterBarComponent implements OnInit {

    @ViewChild('FilterPanelComponent', {static : false}) filterPanel: FilterPanelComponent;

    public values1: string[] = ['Philips'];

    public values2: string[];

    constructor() {
      //this.values2=this.filterPanel.activeFilters;  
    }

    ngOnInit() {
        //console.log(this.values2);
    }
}

Проведя дополнительные исследования, я понял, что бессмысленно использовать @ViewChild в этом сценарии. Поэтому я попытался сделать услугу. Я пытался @Input(). Я также попробовал это: Как использовать переменную из компонента в другом в Angular2 . но я все еще не могу реализовать решение. Пожалуйста, поправьте меня.

Ответы [ 2 ]

2 голосов
/ 06 марта 2020

Вы можете создать службу для совместного использования данных между компонентами,

Новая служба, называемая filter-panel.service.ts file с setter () и getter () метод,

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

@Injectable()
export class FilterPanelService {

  filterdata: any[];
  constructor() { }

   get data(): any{
    return this.filterdata;
  }

  set data(val: any){
    this.filterdata = val;
    console.log(this.filterdata);
  }

}

В filter-panel.component.ts установите значение как,

export class FilterPanelComponent implements OnInit {

    public activeFilters: string[];
    public text: string="hello world";

    constructor(public filterPanelService:FilterPanelService) {

        this.activeFilters = [
            'Provider: CMS',
            'Region: All',
            'Provider Group:All',
            'Provider: CMS',
            'Region: All',
            'Provider Group: All'
        ];

        this.filterPanelService.data = this.activeFilters;
    }

    ngOnInit() {}
}

И в filter-bar.component.ts получите значение, как ,

export class FilterBarComponent implements OnInit {
    @ViewChild('FilterPanelComponent', {static : false}) filterPanel: FilterPanelComponent;


    public values1: string[] = ['Philips'];

    public values2: string[];


    constructor(public filterPanelService: FilterPanelService) {

      //this.values2=this.filterPanel.activeFilters;  
    }

    ngOnInit() {
        //console.log(this.values2);
        console.log('value received ', this.filterPanelService.data);
    }
}

Рабочая Stackblitz ..

1 голос
/ 06 марта 2020

Если оба компонента не имеют родительских и дочерних отношений и если вы хотите передать данные между ними, вы можете реализовать тему RxJS для одного и того же. Я надеюсь, что это поможет вам

Служба сообщений

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

@Injectable({ providedIn: 'root' })
export class MessageService {
    private subject = new Subject<any>();

    sendMessage(message: string) {
        this.subject.next({ text: message });
    }

    clearMessages() {
        this.subject.next();
    }

    getMessage(): Observable<any> {
        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);
     })
    }
}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...