【问题标题】:BehaviorSubject issue, next() not workingBehaviorSubject 问题,next() 不起作用
【发布时间】:2020-08-22 02:18:41
【问题描述】:

我正在尝试使用 Angular 服务通过 observable 存储和通信数据。

这是我的服务

public _currentLegal = new BehaviorSubject({
  name: 'init',
  _id: 'init',
  country: 'init',
  city: 'init',
});
readonly currentLegal$ = this._currentLegal.asObservable();

constructor(private http: HttpClient) {
}

setCurrentLegal(legal) {
  const legaltest = {
    name: 'test',
    _id: 'test',
    country: 'test',
    city: 'test',
  }
console.log('emitting next value from', legal.name)
this._currentLegal.next({ ...legaltest });
}

我有一个调用 setCurrentLegal 的组件,console.log 被触发并且正确。然后我导航到另一个订阅 currentLegal$ observable 的组件,并且值仍然相同(init)!

我尝试通过设置公共类型并使用 getValue() 直接访问该值,同样。 我尝试复制对象以不传递引用,没有改变任何东西。

这是我的下标组件 ngOnInit :

ngOnInit(): void {
  this.legalToUpdate = this.legalService.currentLegal$.subscribe((legal) => {
    console.log(legal)
  })
}

这里有什么问题? 谢谢

【问题讨论】:

  • 不共享服务状态的两个组件是什么关系?似乎每个组件都有新的服务实例。 PS:你可以只做currentLegal$: Observable<yourType> = this.currentLegal,如果不需要初始值并且不需要.getValue,你可能想使用ReplaySubject

标签: javascript angular observable behaviorsubject


【解决方案1】:

你有这种行为是因为你在不同的模块中使用它并且它被创建了不同的实例。

将您的服务放在根目录中:

@Injectable({ providedIn: 'root' })
export class LegalService implements HttpInterceptor { }

【讨论】:

  • 是的,我一直在使用 providedIn: 'root' :s 而且我只在我的一个模块中提供这项服务
  • @Julien FEGER 把console.log放到构造函数下,看看创建了多少实例
  • 是的,你是对的,我从我的模块提供程序中删除了它,因为它默认是在 root 中提供的。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-07
  • 2013-01-05
  • 2014-05-07
  • 1970-01-01
相关资源
最近更新 更多