代码之家  ›  专栏  ›  技术社区  ›  k.vincent

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

  •  2
  • k.vincent  · 技术社区  · 8 年前

    我正在尝试根据属性状态禁用/启用组件中的按钮 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 始终保持状态: false 在组件中 ts html

    如果我执行该功能: connectionRetry() 直接在 *.组件。ts ,它直接工作,但不是通过服务。这和角度消化循环有关吗?

    我一直在搜索(也在SOF中)并尝试不同的方法,但不幸的是没有成功。其实看起来很简单。

    1 回复  |  直到 8 年前
        1
  •  1
  •   Julius Dzidzevičius    8 年前

    你也可以用通常的方式通过 主题 行为主体

    服务:

    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、 通常最好将Subject保持为类作用域私有,并创建另一个实例- public btnSubject$ = this.$btnSubject.asObservable() 并订阅它。


    旧帖子:

    当你经过时 this.isBtnDisabled retryWhen() 只需传递它的值,而不是对象的引用。

    我不知道你想定在什么时候 isBtnDisabled 这是真的,所以也许有更好的方法,但我认为这也是可以的-你可以简单地引用它 ISBTN禁用 :

    .subscribe(
      res => {this.triggerBtn = this.mainService.triggerBtn }
    
    推荐文章