簡體   English   中英

BehaviorSubject 問題,next() 不起作用

[英]BehaviorSubject issue, next() not working

我正在嘗試使用 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() 直接訪問該值,同樣。 我嘗試復制 object 以不通過參考,沒有改變任何東西。

這是我的下標組件 ngOnInit:

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

這里有什么問題? 謝謝

您有這種行為是因為您在不同的模塊中使用它並且它被創建了不同的實例。

將您的服務放在根目錄中:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM