【问题标题】:Modify view inside event handler before view ready在视图准备好之前修改事件处理程序中的视图
【发布时间】:2019-12-28 11:13:06
【问题描述】:

当我的 nativescript 应用程序启动时,我有一个类负责登录并向我发送事件以通知当前状态。在登录过程中(通常需要 1 到 5 秒),我收到了许多更新事件,并且必须显示一个忙碌指示符,以便用户知道正在发生某些事情......

我的问题是当我的事件被触发时,用户界面还没有准备好(我想afterViewInit此时还没有被调用),因此hide/show方法我的LoadingIndicator 产生异常。

我正在使用来自@nstudio/nativescript-loading-indicatorLoadingIndicator。这是我的主页.component.ts 中的事件处理程序示例:

private onUserLogin(info: LoginInfo): void {
   if (info == null) {
      this.loadingIndicator.show();
   } else {
      this.loadingIndicator.hide();
   }
}

我不确定解决方案。在我的onUserlogin 事件处理程序中使用setTimeout 执行循环以等待afterViewInit 事件已被触发似乎不是一个好主意.....

【问题讨论】:

  • 你想在这里得到什么结果,你想显示加载指示器吗?还是只处理异常?如果是后者,我建议将 loadingIndicator 函数调用包装在 try/catch 块中。
  • 我必须显示它,因为正在处理登录(我想通知用户)。至少在视图准备好后。
  • 那么您可以在afterViewInit 中设置isLoaded 标志为真,然后仅在为真时调用 loadingIndicator 函数?或者您只能将onUserLogin() 设置为afterViewInit 中的登录处理程序(不过我不知道您如何调用onUserLogin(),您好吗?)。
  • 就像写的一样,onUserLogin 是另一个类触发的事件,它告诉我正在处理登录。它可以随时触发,也可以在视图未初始化时触发,这正是问题所在......我目前的解决方法是一个肮脏的解决方案,其中 setTimeout 等待标志设置为 true(在 afterViewInit 方法中...... .)
  • 那么我就得到了isLoaded 标志方法。

标签: angular typescript nativescript


【解决方案1】:

与 Angular 中的任何异步操作一样,推荐的模式是使用带有 BehaviorSubject() 的共享服务。这将异步事件与组件分离,并允许组件只关注视觉副作用。

@Injectable()
export class LoginService {
    public info$ = new BehaviorSubject<LoginInfo>(null);

    public onUserLogin(info: LoginInfo) {
        this.info$.next(info);
    }
}

您现在可以从组件订阅这些事件,但要在视图准备就绪时进行。

@Component({...})
export class ExampleComponent implements OnDestroy, OnInit {
    private destroyed$ = new Subject<void>();

    public constructor(private login: LoginService) { }

    public ngOnDestroy() {
       this.destroyed$.next();
       this.destroyed$.complete();
    }

    public ngOnInit() {
       this.login.info$.pipe(
          takeUntil(this.destroyed$)
       ).subscribe(info => {
           if (info == null) {
               this.loadingIndicator.show();
           } else {
               this.loadingIndicator.hide();
           }
       });
     }
}

【讨论】:

  • 谢谢!实际上这或多或少是我正在做的事情,我应该在我的问题中发布更多代码,我的错......与你的唯一区别是我订阅ngAfterViewInit事件而不是ngOnInit和我在ngOnDestroy 中做了一个unsubscribe,但它仍然不起作用(但我的问题中提到的setTimeout 解决方法正在起作用)
  • 这是我在 Nativescript 中已经观察到的一个问题,ngAfterViewInit 事件似乎被触发得太早了,至少有时是这样。我现在做的是订阅我的主布局的(loaded) 事件,并将订阅代码放在这个处理程序中,它工作正常。奇怪的。会接受这个答案,因为它帮助我找到了解决方案....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多