【问题标题】:Run function after an observable variable is initialized初始化可观察变量后运行函数
【发布时间】:2019-07-24 22:55:50
【问题描述】:

我正在 Angular 中使用 socket.io 设置聊天应用程序。在通过订阅初始化可观察变量后,我在运行代码/函数时遇到问题。初始化后的特定代码应该向下滚动到最新消息,但它触发得太早了。

我认为问题是因为下面的变量chatList 没有足够的时间来获取消息列表。

使用setTimeout(() => {/*scroll function here*/}, 1); 有效,但根本不理想。

this.getMessages()
  .subscribe((chat: string[]) => {
    this.chatList$ = chat;

    //I want the code below to run once the code above is fully Initialized.
     this.conversationList.nativeElement.scrollTop = this.conversationList.nativeElement.scrollHeight;
  });

observable 完成后运行代码/函数的正确方法是什么?

【问题讨论】:

  • 你的意思是你想让UI使用this.chatList$并创建所有的DOM,然后你调用另一个函数?你问的是这个吗?
  • 使用像this.chatList$ 这样的美元符号通常意味着变量是可观察的,所以我认为你这样做很奇怪。更重要的是,我没看懂你在问什么,能不能把相关的模板代码加进去?
  • 这听起来可能很愚蠢,但是您是否在页面加载后立即滚动?如果您希望用户立即看到某些内容,为什么不将其放在页面顶部,然后坐下来让页面自然呈现并完全避免滚动?
  • @frosty 是的,这就是我的意思。这么说来,问题好像出在 DOM 没有及时渲染上?
  • @KeenanDiggs 我明白了,感谢您的澄清。我不应该在这里使用美元符号。 渲染聊天列表的模板代码: <div *ngFor="let item of chatList">(移除美元符号)

标签: angular typescript socket.io rxjs observable


【解决方案1】:

使用MutationObserver 查看包含您的子列表的父节点。然后使用subject 从回调中发出信号,表明列表已准备好进行滚动。理论上应该可以的

this.childReady=new Subject()
// replace the dom select with your angular viewChild nativeElement
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = {childList: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
        if (mutation.type == 'childList') {
              this.childReady.next(true)
        }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

this.getMessages().pipe(
  tap((chat: string[]) => {
    this.chatList$ = chat;
   }),
   switchMap(()=>this.childReady())
).subscribe(()=>{
     this.conversationList.nativeElement.scrollTop = this.conversationList.nativeElement.scrollHeight;

})

【讨论】:

    猜你喜欢
    • 2016-07-28
    • 1970-01-01
    • 2013-02-28
    • 2021-07-08
    • 2022-12-14
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多