ANGULAR - 订阅组件不更新服务的值



我的服务中有一个要订阅的可观察对象。

由于BehaviorSubject,第一次返回了良好的初始值。

但是当我在服务中使用next((更新值时,我的组件中的subscribe不会被调用。。。

这是我服务中的代码:

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

我的错误在哪里?我很乐意学习,因为我已经尝试了很多事情,但在这一点上什么都不起作用。。。

谢谢大家!

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

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

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

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

希望它能帮助

我给你一个简单的架构,它尊重POO、reactive&清洁代码原理

checkbox.service.ts&复选框.组件.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()">

最新更新