如何从服务更改/控制按钮状态(布尔值)?



我正在尝试根据属性状态false/true禁用/启用组件中的按钮。此状态根据 if 语句在服务中更改。

*.service.ts

public connectionRetry(
initialDelay,
maxRetry,
errorWhiteList,
triggerBtn,
) {
return (errors) => errors.scan((retryAttempts, error) => {
if ( retryAttempts < maxRetry ) {
triggerBtn = true;
}
if ( !errorWhiteList.includes(error.status ) || retryAttempts > maxRetry) {
triggerBtn = false;
throw error;
}
return retryAttempts + 1;
}, 0).switchMap((retryAttempts) => {
let delay = Math.pow(2, retryAttempts - 1) * initialDelay;
return Observable.timer(delay);
});
}

*.component.ts

public isBtnDisabled = false;
constructor ( public mainService: MainService, public mainUtils: MainUtils ) {}
public storeData(paramX, paramY) {
this.mainService.addUser(paramX, paramY)
.retryWhen(
this.mainUtils.connectionRetry(
xxx, 
xxx, 
[xxx], 
this.isBtnDisabled,
))
.subscribe(
res => {....},
error = > {...}
);
} 

*.component.html

<button [disabled]="!form.valid || isBtnDisabled">button text</button>

问题是我就是无法使这个概念起作用......属性isBtnDisabled始终保持状态:组件中的falsetshtml

如果我实现该功能:直接在*.component.tsconnectionRetry(),它可以直接工作,但不是通过服务。它与角消化周期有关吗?

我一直在寻找(也在 SOF 中(并尝试不同的方法,但不幸的是没有成功。实际上似乎很简单。

您也可以执行常规方式 - 通过SubjectBehaviorSubject

服务:

public $btnSubject = new BehaviorSubject<boolean>();

现在,每当您需要将 false 更改为 true,反之亦然,只需next(//true or false)

return (errors) => errors.scan((retryAttempts, error) => {
if ( retryAttempts < maxRetry ) {
this.$btnSubject.next(true)
}

并在组件中订阅该主题:

ngOnInit() {
this.mainService.$btnSubject.subscribe(val => this.isBtnDisabled = val)
}

p.s. 通常最好将主题保密到类范围并创建另一个实例 -public btnSubject$ = this.$btnSubject.asObservable()并订阅它。


旧帖子:

当您将this.isBtnDisabled传递给retryWhen()时,您只传递它的值,而不是对象的引用。

我不确定您想在什么时候将isBtnDisabled设置为 true,所以也许有更好的方法,但我认为这也没关系 - 您可以简单地参考该isBtnDisabled

.subscribe(
res => {this.triggerBtn = this.mainService.triggerBtn }