I want to share data between 2 sibling components.
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.