等待功能完成if

时间:2018-02-22 19:51:02

标签: angular typescript ionic3

我正在尝试进行测试,但它不等待在数据库中发出请求,看起来该函数返回undefined,并且只有在请求后它返回true或false并且测试落在else上。

我的问题出在角度为4/5的RestService

执行密码验证以执行更新的功能

scipy.integrate.dblquad

检查密码功能

    handler: data => {
      if (this.checkPassword(data.password)) {
        console.log("4--------");
        // logged in!
        let jsonCreate = {
            name: form.value.inputName,
            email: form.value.inputEmail,
            password: form.value.inputPassword,
            description: form.value.inputDescription,
            id: this.id
        };
        console.log('jsonCreate');
        console.log(jsonCreate);
        //adiciona cliente ao banco
        this.rest.put('usersClient/atualizacao', jsonCreate)
        .subscribe(userUpdated => {
            console.log(userUpdated);

        });
      } else {
        console.log("3--------");
        return false;
      }
    }

1 个答案:

答案 0 :(得分:1)

为了等待异步操作,您必须返回this.rest.post创建的observable:

public checkPassword(password){
    ...
    return this.rest.post('Login/clientAuth', "").map(user => !this.isEmptyObject(user));
});

然后,在data中订阅此可观察对象:

handler: data => {
    this.checkPassword(data.password).subscribe(isLoggedIn => {
        if (isLoggedIn) {
            let jsonCreate = {
                ...
            };

            this.rest.put('usersClient/atualizacao', jsonCreate).subscribe(userUpdated => {
                console.log(userUpdated);
            });
        } else {
            return false;
        }
    });
}

注意:如果您还需要等待put之外的data操作,则无法订阅checkPassword。你需要做这样的事情:

handler: data => {
    this.checkPassword(data.password).flatMap(isLoggedIn => {
        if (isLoggedIn) {
            let jsonCreate = {
                ...
            };
            return this.rest.put('usersClient/atualizacao', jsonCreate).map(userUpdated => {
                console.log(userUpdated);
            });
        } else {
            return false;
        }
    });
}

订阅data