简体   繁体   English

HttpClient post返回true,但组件订阅function为false

[英]HttpClient post returns true, but component subscribe function is false

I am trying to log in from a button.我正在尝试从按钮登录。 I have template input fields with two-way binding to set the string values of username and password.我有带有双向绑定的模板输入字段来设置用户名和密码的字符串值。 By event binding, the login button triggers a login() method.通过事件绑定,登录按钮触发 login() 方法。 This login method creates a local Credential object which absorbs the username and password.此登录方法创建一个本地凭据 object,它吸收了用户名和密码。 The Credential object is passed to the HttpClient service method.凭证 object 被传递给 HttpClient 服务方法。 The service method hits the backend endpoint, and a boolean is passed back which indicates whether the credentials are in the database.服务方法命中后端端点,并传回 boolean,指示凭据是否在数据库中。

In the component class, the service method is subscribed to, and - as I interpret it - during the subscription, a loginSuccess boolean is assigned the value that the service method returns.在组件 class 中,订阅了服务方法,并且 - 正如我解释的那样 - 在订阅期间, loginSuccess boolean 被分配了服务方法返回的值。 Except... my understanding of this must be wrong because this is not happening in the order I would expect.除了......我对此的理解一定是错误的,因为这并没有按照我期望的顺序发生。

login.component.ts登录组件.ts

export class LoginComponent implements OnInit, OnDestroy {
  // credential: Credential;
  username: string;
  password: string;
  user: User;
  loginMessage: string = "";
  loginSuccess: boolean = false;
  userSubscription: Subscription;

  constructor(private userService: UserService) { }

  ngOnInit(): void {
  }
  ngOnDestroy(): void {
    // this.userSubscription.unsubscribe();
  }

  login(): void {
    if(this.username != null){
      var credential: Credential = { username: this.username, password: this.password };
      
      this.userService.authenticateCredential(credential).subscribe(subscribeCheck => { 
        this.loginSuccess = subscribeCheck;
        console.log("mark 04: loginSuccess = " + this.loginSuccess);
      });
      console.log("mark 13: loginSuccess = " + this.loginSuccess);
    }
    console.log("mark 14: loginSuccess = " + this.loginSuccess);

    if(this.loginSuccess){
      console.log("mark 24");
      this.userService.getUser(credential).subscribe(subscriptionUser => {
        this.user = subscriptionUser;
      });
        this.loginMessage = "";
    } else {
      console.log("mark 25");
      this.loginMessage = "LOGIN FAILURE!!!";
    }
  }
}

在此处输入图像描述

The console shows that because the order of execution is not what I expect, the login fails.控制台显示,因为执行顺序不是我期望的,所以登录失败。 The boolean variable loginSuccess always is false when it encounters the if() conditional because the if() conditional is always executed before loginSuccess is assigned by the HttpClient observable. boolean 变量 loginSuccess 在遇到 if() 条件时始终为 false,因为 if() 条件始终在 loginSuccess 由 HttpClient observable 分配之前执行。 Why does this happen?为什么会这样? How can I fix it?我该如何解决?

Your check of if(this.loginSuccess){ should be inside the subscribe.您对if(this.loginSuccess){的检查应该在订阅中。 and you're right the order here matters.你是对的,这里的顺序很重要。

export class LoginComponent implements OnInit, OnDestroy {
      // credential: Credential;
      username: string;
      password: string;
      user: User;
      loginMessage: string = "";
      loginSuccess: boolean = false;
      userSubscription: Subscription;
    
      constructor(private userService: UserService) { }
    
      ngOnInit(): void {
      }
      ngOnDestroy(): void {
        // this.userSubscription.unsubscribe();
      }
    
      login(): void {
        if(this.username != null){
          var credential: Credential = { username: this.username, password: this.password };
          
          this.userService.authenticateCredential(credential).subscribe(subscribeCheck => { 
            this.loginSuccess = subscribeCheck;
            if(this.loginSuccess){
               console.log("mark 24");
               this.userService.getUser(credential).subscribe(subscriptionUser => {
                  this.user = subscriptionUser;
               });
              this.loginMessage = "";
            } else {
               console.log("mark 25");
               this.loginMessage = "LOGIN FAILURE!!!";
            }
            console.log("mark 04: loginSuccess = " + this.loginSuccess);
          });
          console.log("mark 13: loginSuccess = " + this.loginSuccess);
        }
        console.log("mark 14: loginSuccess = " + this.loginSuccess);
    
        
      }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将 HttpClient 订阅数据返回给组件 - How to return HttpClient subscribe data to a component isTokenExpired 方法返回 true 和 false - isTokenExpired method returns true and false 无法访问订阅功能中的组件 - cannot access to this of component in subscribe function Angular 6 - HttpClient 保持订阅服务但将结果传递给组件 - Angular 6 - HttpClient Keeping subscribe in the service but passing the result to the component 监视HttpClient数据-不要在订阅时发布数据 - Monitor HttpClient data - don't post data on subscribe RxJs Angular 7 HttpClient多个POST用forkJoin删除第二个订阅? - RxJs Angular 7 HttpClient multiple POST with forkJoin remove second subscribe? Angular 7中无法访问Angular 7 httpClient.post订阅数据 - Angular 7 httpClient.post subscribe data is not accessible in the angular template AuthGuard 可以激活到函数结束并返回 false 而不是等待订阅返回 true - AuthGuard can activate goes to end of function and returns false instead of waiting for subscription to return true 布尔值设置为false; 如果不带==的if语句返回true - boolean set to false; returns true on if statement without == Angular订阅HTTPClient Observable,错误req.url.toLowerCase不是函数 - Angular subscribe to HTTPClient Observable, error req.url.toLowerCase is not a function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM