BehaviorSubject firing twice

Moh*_*han 6 rxjs angular7

Im using BehaviourSubject from RxJS:

private rights = new BehaviorSubject<Array<string>>([]);


updateRights(rights: Array<string>) {
  this.rights.next(rights);
}

getRights(): Observable<any> {
  return this.rights.asObservable();
}
Run Code Online (Sandbox Code Playgroud)

I'm updating the rights in the root component and im subscribing to it in another component like:

 this.configService.getRights().subscribe(res => {
   console.log(res);
 })
Run Code Online (Sandbox Code Playgroud)

This subscription is firing twice. Once when the data is empty and then again when the data is received.

I want the subscription to fire only once and get only the latest data. What should be done?

djo*_*olf 6

BehaviourSubject默认发出订阅值,这是有意设计的。如果您不想要这种行为,请改用主题


Mas*_*mar 0

这样做:

private currnetRightsSubject: BehaviorSubject<string[]>;
public currentRights: Observable<string[]>;

constructor() {
    this.currnetRightsSubject= new BehaviorSubject<string[]>(/*.......*/);
    this.currentRights= this.currnetRightsSubject.asObservable();
}

public get currentRightsValue(){
    return this.currnetRightsSubject.value;
}
Run Code Online (Sandbox Code Playgroud)

更新

填写BehaviorSubject如下:

this.currnetRightsSubject.next(someValue);
Run Code Online (Sandbox Code Playgroud)