search

Home  >  Q&A  >  body text

javascript - angular2 http In the click event, the first click is undefined, and the value can be obtained only the second time

In the click event of angular2 http, the first click is undefined, and the value can only be obtained after the second click. What is the reason for this and how to implement it? Each click displays a different value?

For example, in the code below, I have obtained the name and password from okLogin(). I assign the returned data to this.result, and then execute isLogin() after the click event occurs, and isLogin will execute okLogin. But I found that when I clicked for the first time, the result was undefined. When I clicked for the second time, I could get the result. However, when the result value changed, the first click still printed out the previous value, which was not the case. The currently obtained value. How to solve it?

okLogin(){
    this.http.get('http://localhost:3000/api/users/login/'+this.Name+'/'+this.Pwd+'')
      .map(res => res.json())
      .subscribe(
        data => this.result=data,
        err => console.error(err),
        () => console.log('done')
      );
  return this.result
  }

isLogin(event){
    if(this.Name===''||this.Name===undefined&&this.Pwd===''||this.Pwd===undefined){
      this.check = true;
    }
    this.check = false;
    this.okLogin();
    // this.result = this.okLogin();
    console.log(this.result);
    if(this.result===true){
      console.log('登录成功')
    }else{
      console.log('发生错误')
    }

The printed effect:
undefined
{data of data}

I initialized the value of result before, but when the incoming username and password changed later, the http.get data had changed, but the result was still the previous value, and it required a second click to display correctly. .

I also encountered this problem when I was doing count before, but the auto-add started directly from 0, and I didn’t want to see 0, I just wanted it to start from 1, so I set a default value for count. is 1

怪我咯怪我咯2785 days ago860

reply all(1)I'll reply

  • 黄舟

    黄舟2017-05-15 17:15:55

    The okLogin() method is written incorrectly. subscribeThere is asynchronous behavior. So when okLogin is called, it will appear that this.result has not been assigned a value, and isLogin will continue to execute.

    Modification plan:

    (1)Promise method
    (2)Modify the way to write subscribe

    okLogin(){
        return this.http.get('http://localhost:3000/api/users/login/'+this.Name+'/'+this.Pwd+'')
          .map(res => res.json());
      }
    
    isLogin(event){
        if(this.Name===''||this.Name===undefined&&this.Pwd===''||this.Pwd===undefined){
          this.check = true;
        }
        this.check = false;
        this.okLogin().subcribe(data=>{
            this.result = data;
            if(data===true){
              console.log('登录成功')
            }else{
              console.log('发生错误')
            }
        })
        

    reply
    0
  • Cancelreply