简体   繁体   中英

Angular 10 - Sharing data between sibling components

I want to share data between 2 sibling components.

  • Component 1: My component 1 is my navbar and it has an option to change the app languange (using ngx- translate), this option is a select with different options.
  • Component 2: My component 2 is a blog with different posts, this posts are saved in a MySQL DB, there are 2 possible languages, the posts are saved in different tables of the DB depending the language there are writed.

So, what we are trying to do is depending the language is selected in component 1 do an http request to the backend passing the actual language selected to get the posts from the correspondent table.

Any idea how to get the languange selected in my component 2 when the select option changes in my component 1?

Since you are using ngx-translate , you can use its service to know which language is selected rather than depending on your component.

@Component({ ... })
export class Component2 implements OnInit {
    constructor(private translate: TranslateService) { }

    ngOnInit() {
        this.translate.onLangChange.subscribe((event: LangChangeEvent) => {
            // run your code
        });
    }
}

Check out the documentation of the ngx-translate library for a list of all the events and properties.

Here you can use RxJS. So you can make service which has BehaviourSubject. And then when you change value in the 1 component you will update this BehaviourSubject value. So in 2 component you can listen to value changes of the subject, and tigger service with different language to get called.

Here is logic within a service:

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

@Injectable({
    providedIn: 'root',
})

export class LanguageService {
    private _languageState: BehaviorSubject<Language> = new BehaviorSubject<Language>();

    constructor() {}

    setLanguageState(lang: Language) {
        this._languageState.next(lang);
    }

    onChangedLanguageState() {
       return this._languageState.asObservable();
    }
}

And then in 1 component when language is switched just update the subject as this.languageService.setLanguageState(lang).

In the 2 component listen to changes as this.languageService.onChangedLanguageState.subscribe(() => {// call http service })

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