简体   繁体   中英

ANGULAR - Subscribe in component don't update value from service

I have a observable in my service that I want to subscribe.

In the first time, the good initial value is returned, thanks to BehaviorSubject.

But when I update the value using next() in my service, the subscribe in my component is not called...

This is the code in my service:

    activeDeepView:any = false;
    deepViewStatus: Subject<boolean> = new BehaviorSubject<boolean>(false);

    deepView(){
      this.activeDeepView = !this.activeDeepView;
      this.deepViewStatus.next(this.activeDeepView);
      console.log("deep view status", this.deepViewStatus);
    }

And this is the code in my component:

this.globalFn.deepViewStatus.subscribe(value => {
  console.log(value);
  if(value == true){
    this.renderer.setStyle(this.fsModal.nativeElement,'transition','0.3s ease-out');
    this.renderer.setStyle(this.fsModal.nativeElement,'pointer-events','all');
    this.renderer.setStyle(this.fsModal.nativeElement,'transform','translateY(0px)');
  } else {
    this.renderer.setStyle(this.fsModal.nativeElement,'transition','0.3s ease-out');
    this.renderer.setStyle(this.fsModal.nativeElement,'pointer-events','none');
    this.renderer.setStyle(this.fsModal.nativeElement,'transform','translateY(1000px)');
  }
})

Where is my error? I'll be glad to learn, because I've try many things and nothing works at this point...

Thank you all !

You can try to expose BehaviorSubject as an Observable. In your service:

private deepViewStatus: Subject<boolean> = new BehaviorSubject<boolean>(false);
...
status(): Observable<boolean> {
  return  this.deepViewStatus.asObservable();
}

And then you would subscribe in your component this way:

this.yourService.status().subscribe(value => {//your code})

Hope it helps

I give you a simple architechture that respects POO, reactive & clean code principles

checkbox.service.ts & checkbox.component.ts

@Injectable()
export class CheckBoxService {
  private _stream$ = new BehaviorSubject<boolean>(false);

  constructor() {}

  public getStream$(): Observable<boolean> {
     return this._stream$();
  }

  public toggle() {
    const currentValue = this._stream$.getValue();
    this._stream$.next(!currentValue);
  }
}

@Component()
export class CheckBoxComponent implements OnInit {
  private isSelected$ = new Observable<boolean>();

  constructor(
    private checkBoxService: CheckBoxService
  ) {}

  public ngOnInit() {
    this.isSelected$ = this.checkBoxService.getStream$();
  }

  public checkboxToggled() {
    this.checkBoxService.toggle();
  }
}

checkbox.component.html

 <input type="checkbox" [ngModel]="isSelected$ | async" (ngOnChanges)="checkboxToggled()">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM