【发布时间】:2021-09-05 01:49:27
【问题描述】:
我有一个奇怪的问题。我在一项服务中定义了BehaviourSubject,以在用户更改语言时传播更改。在许多组件中,当BehaviourSubject 更改时,我会做一些事情。它适用于除一个以外的所有组件,我不知道为什么。
我的代码:
@Injectable()
export class I18nLanguagesService {
private activeLang: I18NLanguage = LANGUAGES.find(ln => ln.name === 'Español');
activeLangSubject = new BehaviorSubject<I18NLanguage>(null);
setActiveLang(language: I18NLanguage): void {
this.activeLang = language;
this.activeLangSubject.next(language);
}
getActiveLang(): I18NLanguage {
return this.activeLang;
}
getLanguages(): I18NLanguage[] {
return LANGUAGES;
}
}
在CoreModule的providers部分声明,在app.module中导入一次。
用法:
组件 1(在
shared.module中定义)
这个很好用。每次主题发出一个值时,它都会调用服务。
constructor(private statesServ: StatesService, private i18nSrv: I18nLanguagesService) {}
this.i18nSrv.activeLangSubject
.pipe(
tap(() => {
this.statesMultiCtrl.reset();
console.log('SELECTOR | In tap')
}),
switchMapTo(this.statesServ.getStatesList())
)
.subscribe(states => {
this.states = states;
this.statesFiltered = this.states;
});
管道(在
shared.module中定义)
它也适用于管道:
export class AsyncI18nDatePipe implements PipeTransform {
constructor(private i18nS: I18nLanguagesService) {}
transform(value: Date | null | undefined, format = 'mediumDate', timezone?: string): Observable<string> {
if (value) {
return this.i18nS.activeLangSubject.pipe(map(localeId => formatDate(value, format, localeId.countryCode, timezone)));
}
return of('');
}
}
故障出在这个组件中,也在shared.module中定义:
constructor(private formBuilder: FormBuilder, private valUsuServ: ValidationUsersService, private cmpServ: CampaignsService, private i18nService: I18nLanguagesService) {
this.filters = this.formBuilder.group({
idClient: new FormControl(null),
idProject: new FormControl({ value: null, disabled: true }),
sourceLanguage: new FormControl({ value: null, disabled: true }),
targetLanguage: new FormControl({ value: null, disabled: true }),
rangeDate: new FormGroup({
dateFrom: new FormControl(null),
dateTo: new FormControl(null),
}),
idItem: new FormControl({ value: null, disabled: false }),
searchWords: new FormControl({ value: null, disabled: true }),
itemState: new FormControl(null),
category: new FormControl({ value: null, disabled: true }),
validationUser: new FormControl({ value: null, disabled: true }),
campaing: new FormControl(null),
priorityOrd: new FormControl('asc'),
dateOrd: new FormControl('asc'),
categoryOrd: new FormControl('asc'),
campaingOrd: new FormControl('asc'),
});
}
ngOnInit(): void {
this.i18nService.activeLangSubject.pipe(tap(lang => console.log('FILTERS | In tap -->', lang)));`
}
但是当我更改语言时,仅在“有效”的组件中,它会记录更改:
我不知道为什么会发生这种行为,任何帮助将不胜感激。感谢阅读!!
【问题讨论】:
-
你在哪里订阅 observable?你说它有时有效,但你没有包含任何代码,你在失败的组件中实际使用
subscribe或async管道订阅。
标签: angular typescript rxjs behaviorsubject