Steinfeld
Steinfeld

Reputation: 689

Angular 6 how to wait for httpclient to return

I am trying to call a function on my flask interface from Angular 6. A function that should verify some credentials upon a click and according to the response either show an error or navigate to a page.

Thought I can not seem to be able to find a way to wait for the response before executing the next line of code. This causes a bug where the button needs to be pressed twice for the navigation to happen.

I tried using asyc/await, tried using .then, tried switching the subscribe to map but nothing works.

I guess I am missing something critical.

onClick() {
    let data = {
        // some data
    }
    let response = this.login(data);
    if (response["valid"] === true) {
        this.router.navigate(['/cool_page']);
    }
}

login(data) {
    let login_data = {}
    this.httpClient.post('http://somedomain.com/login', JSON.stringify(data)).subscribe( response => {
        login_data = response;    
    });

    return login_data; //this remains empty
}

Upvotes: 1

Views: 6558

Answers (1)

Sunil
Sunil

Reputation: 11241

It require small correction related to Subscription.

onClick() {
    let data = {
        // some data
    }
     let response = this.login(data).subscribe( response => {
        if (response["valid"] === true) {
        this.router.navigate(['/cool_page']);
      }
    });

}

login(data) {
    let login_data = {}
    return this.httpClient.post('http://somedomain.com/login', JSON.stringify(data));
}

Upvotes: 3

Related Questions