Angular BehaviorSubject未更新变量
我在谷歌甚至StackOverflow上搜索了一个解决方案,甚至尝试了很多解决方案,但似乎都不起作用。这是我的问题 爱奥尼亚4项目:父组件包含标题组件和内容组件。标头调用behaviorsubject服务来设置变量,内容组件显示该变量。这不起作用(通过标题更改变量不会更新内容中的变量) 过滤服务Angular BehaviorSubject未更新变量,angular,ionic4,behaviorsubject,Angular,Ionic4,Behaviorsubject,我在谷歌甚至StackOverflow上搜索了一个解决方案,甚至尝试了很多解决方案,但似乎都不起作用。这是我的问题 爱奥尼亚4项目:父组件包含标题组件和内容组件。标头调用behaviorsubject服务来设置变量,内容组件显示该变量。这不起作用(通过标题更改变量不会更新内容中的变量) 过滤服务 import { Injectable } from '@angular/core'; import { Observable, BehaviorSubject } from 'rxjs'; @Inj
import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class FilterService {
private filter:BehaviorSubject<string>;
constructor() {
this.filter = new BehaviorSubject<string>('');
}
setFilter(flt: string): void
{
this.filter.next(flt);
console.log('filter set to ', flt);
}
getFilter()
{
return this.filter.asObservable();
}
}
内容文件
import { FilterService } from '@app/services/filter/filter.service';
// ... other stuff
public thefilter = '';
constructor(
private filterService: FilterService){}
ngOnInit() {
this.filterService.getFilter().subscribe((val)=>{this.thefilter=val});
// this.thefilter doesn't update. Why???
// ...
我花了好几天的时间在这上面,都没有用!有什么建议吗?试试这个,你需要通过管道来观察。OnDestroy管理订阅 这与View Facades+RxJS模式非常相似: 下面是rxjs facade模式的一个示例:
导出类MyClass实现OnDestroy
公共过滤器=“”;
private onDestroy=新主题();
建造师(
专用筛选器服务:筛选器服务{}
ngOnInit(){
this.filterService.getFilter().pipe(takeUntil(this.ondestory)).subscribe((val)=>{this.thefilter=val});
恩贡德斯特罗(){
this.ondestory.next();
this.ondestory.complete();
}
我已经重新创建了您的代码,效果很好:您可以拿我的示例并尝试重新创建错误吗?谢谢,如果从同一个文件调用,效果很好。在我的例子中,头是一个组件,内容是另一个组件。我在头中调用setFilter(),在内容中调用getFilter(),它没有显示新值。
import { FilterService } from '@app/services/filter/filter.service';
// ... other stuff
public thefilter = '';
constructor(
private filterService: FilterService){}
ngOnInit() {
this.filterService.getFilter().subscribe((val)=>{this.thefilter=val});
// this.thefilter doesn't update. Why???
// ...
export class MyClass implements OnDestroy
public thefilter = '';
private onDestroy = new Subject<void>();
constructor(
private filterService: FilterService){}
ngOnInit() {
this.filterService.getFilter().pipe(takeUntil(this.onDestroy)).subscribe((val)=>{this.thefilter=val});
ngOnDestroy() {
this.onDestroy.next();
this.onDestroy.complete();
}