Angular 6 run a function in every X seconds

后端 未结 5 1392
我寻月下人不归
我寻月下人不归 2021-01-03 21:53

I have a function called

opensnack(text) { ... };

which is opening an angular material snackbar with the given text input.

What I

5条回答
  •  悲&欢浪女
    2021-01-03 22:43

    export class AComponent implements OnInit {
      id: string = "1";
      mySub: Subscription;
    
      constructor(private http: HttpClient) {
        this.mySub = interval(8000).subscribe((func => {
          this.onIdSelect(this.id);
        }))
      }    
      ngOnInit(): void {
      }
      onIdSelect(id) {
        this.http.post('https://jsonplaceholder.typicode.com/posts', id).subscribe((res => {
          console.log(res);
        }))
        // this.mySub.unsubscribe(); 
      }
    }
    

    Import the interval and Subscription from rxjs. Here, code is calling the onIdSelect() method every 8seconds. So post response will be printed on the console after every 8seconds. If you want to call the method only once after 8seconds, then just unsubscribe the mySub variable.

提交回复
热议问题