get value from another component angular 4

2020-02-17 10:27发布

问题:

I have two separate components; a header component containing a select search box, stats component that shows the results depending on the value of the select box, I was wondering if it's possible to refresh the results once the select box change, I thought about using the LocalStorage but it seems like a lazy solution.

回答1:

Use Shared Services:

Service:

@Injectable()
export class MyService {
    myMethod$: Observable<any>;
    private myMethodSubject = new Subject<any>();

    constructor() {
        this.myMethod$ = this.myMethodSubject.asObservable();
    }

    myMethod(data) {
        console.log(data); // I have data! Let's return it so subscribers can use it!
        // we can do stuff with data if we want
        this.myMethodSubject.next(data);
    }
}

Component1 (sender):

export class SomeComponent {
    public data: Array<any> = MyData;

    public constructor(private myService: MyService) {
        this.myService.myMethod(this.data);
    }
}

Component2 (receiver):

export class SomeComponent2 {
    public data = {};

    public constructor(private myService: MyService) {
        this.myService.myMethod$.subscribe((data) => {
                this.data = data; // And he have data here too!
            }
        );
    }
}

Check documentation!



回答2:

The best way is to send the data to the component.

Use the @input property to send the data to controller. Then implement ngOnChanges and execute the function to load the data.

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
    selector: 'second-component',    
})

@Injectable()
export class SecondComponent implements OnChanges {

    @Input()
    selectValue: string;

    ngOnChanges(changes: SimpleChanges) {
           if (changes['selectValue']) {
             //call your function to load the data
           }
    }

}

uses

<second-component [selectValue]="bindYourValue"></second-component>


回答3:

I think that the best for your case would be to use service for communication between components.

Check out example in Angular documentation: https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service



标签: angular