【问题标题】:ANGULAR - Subscribe in component don't update value from serviceANGULAR - 在组件中订阅不更新服务的值
【发布时间】:2020-04-10 10:01:51
【问题描述】:

我的服务中有一个我想订阅的 observable。

在第一时间返回良好的初始值,感谢 BehaviorSubject。

但是当我在服务中使用 next() 更新值时,不会调用组件中的订阅 ...

这是我服务中的代码:

    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);
    }

这是我组件中的代码:

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)');
  }
})

我的错误在哪里?我会很高兴学习,因为我已经尝试了很多东西,但目前没有任何效果......

谢谢大家!

【问题讨论】:

  • deepView() 是从您的订阅所在的同一组件中调用的,还是从其他地方调用的?
  • 您好!感谢您的回答,它是从另一个组件调用的,providerIn:root 在我的服务中,它必须在组件中?
  • 听起来你有一个标准设置。你能在 stackblitz 中重现你的问题吗?
  • 是偶然完成的吗?这看起来不错,向我们展示代码的其他部分

标签: angular rxjs


【解决方案1】:

您可以尝试将 BehaviorSubject 公开为 Observable。 为您服务:

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

然后你会以这种方式订阅你的组件:

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

希望对你有帮助

【讨论】:

  • 感谢您的回答,但它不起作用,没有任何反应......:/
【解决方案2】:

我给你一个简单的架构,它尊重 POO、响应式和干净的代码原则

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

&lt;input type="checkbox" [ngModel]="isSelected$ | async" (ngOnChanges)="checkboxToggled()"&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-12
    • 2020-10-26
    • 2019-11-25
    • 2017-10-13
    • 1970-01-01
    相关资源
    最近更新 更多