在Angular / Typescript中几秒钟后删除/拼接数组元素

时间:2017-08-10 07:51:42

标签: arrays angular typescript

我得到了这个代码,只要服务器注册新的呼叫者,它就会将呼叫者添加到数组中。

caller = new CallerData;
callers = new Array<CallerData>();

ngOnInit() {
            this.callService.exposeCallerObservable().subscribe(
                (x: CallerData) => {
                    this.caller = x;
                    this.callers.push(x);
           },
                (error: any) => {
                    console.warn("Could not subscribe to the Caller Observable!", error);
                }
            )
        }  

现在我想让每个调用者在数组中保持5-10秒,在此之后它应该再次删除。你能帮帮我吗?

1 个答案:

答案 0 :(得分:5)

您可以使用js setTimeout功能

ngOnInit() {
    this.callService.exposeCallerObservable().subscribe(
        (x: CallerData) => {
            this.caller = x;
            this.callers.push(x);
            setTimeout(()=>{
                if(this.callers && this.callers.length > 0){
                    this.callers.shift();
                }
            },5000);
         }, 
         (error: any) => {
             console.warn("Could not subscribe to the Caller Observable!", error);
         });
}