2017-08-10 73 views
0

只要服務器註冊新的調用者,我就得到了此代碼,它將調用者添加到數組中。在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秒的數組,並在這段時間後,它應該再次被刪除。你能幫助我嗎?

+3

後'this.callers.push(X);'可以寫像'的setTimeout(()=> {this.callers = [];} ,5000)' – echonax

+0

完美!感謝這就是我一直在尋找:) – reveN

+0

我會提供它作爲一個答案,然後:-) – echonax

回答

3

可以使用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); 
     }); 
} 
+1

這將一次刪除所有呼叫者。我不確定那是OP想要的。我的意思是如果每秒都有一個呼叫者被髮射出去呢?然後第五個將立即被刪除 –

+1

@TamasHegedus,因爲OP評論說:「完美!謝謝,這就是我正在尋找的:」_「我認爲這是OP所尋找的:-),但當然可以使用拼接去除特定元素。 – echonax

+0

tamas其實是對的:D我評論了這個問題^^ – reveN