如何延迟打字稿?

时间:2018-07-01 18:24:48

标签: html angular angular-material spinner

首先使用角度。我在登录组件时遇到问题,我想在用户输入详细信息并从服务器获取响应后显示微调器几秒钟...现在一切都很快发生,我无法像我想要的那样在7秒钟内看到微调器到..我该如何延迟应用程序以便看到它?这是我的代码:

组件:

RedisTemplate<String,String> redisTemplateForAllValues;

html:

 showSpinner: boolean = false;

  showMySpinner() {
  this.showSpinner = true;
  setTimeout(() => {
    this.showSpinner = false;
  }, 7000);
  }

  constructor(private dataService: DataService, private auth: AuthService, 
  public matService: MatService) { }

  loginUser(username, password, type): void {

  switch (type.value) {

  case "ADMIN": {
    this.dataService.getLoginResponse(username.value, password.value, 
     type.value).subscribe(res => {
      **this.showMySpinner();** HERE I USE THE FUNCTION BUT IT GOES RIGHT UNDER IT AND DONT LET IT SHOW
      this.auth.updateUserType(type.value);
      sessionStorage.setItem("type", "ADMIN");
      sessionStorage.setItem("username", username.value);
      this.matService.openSnackBar(this.loginSuccess, "success");
    }, error => this.matService.openSnackBar(this.loginFailed, "error"));
    break;
    }

谢谢

2 个答案:

答案 0 :(得分:1)

您可以使用rxjs delay

您可以在delay本身的getLoginResponse()方法中添加DataService。并相应地在组件文件中切换微调器。

data.service.ts

import {delay} from 'rxjs/operators'

getLoginResponse() {
  return this.http.get(url).pipe(delay(7000));
}

component.ts

switch (type.value) {
 case "ADMIN": {
    this.showSpinner = true; // start spinner just before asynchronous request is sent
    this.dataService.getLoginResponse(username.value, password.value, 
     type.value).subscribe(res => {
      this.showSpinner = false; // stop spinner
      this.auth.updateUserType(type.value);
      sessionStorage.setItem("type", "ADMIN");
      sessionStorage.setItem("username", username.value);
      this.matService.openSnackBar(this.loginSuccess, "success");
    }, error => this.matService.openSnackBar(this.loginFailed, "error"));
    break;
}

DEMO

答案 1 :(得分:0)

您需要在呼叫之前启动微调器。

this.showSpinner = true;
this.dataService.getLoginResponse(username.value, password.value, 
     type.value).subscribe(res => {
      this.showSpinner = false;
      ...
    }, error => this.matService.openSnackBar(this.loginFailed, "error"));
    break;