1

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
}
Steinfeld
  • 649
  • 2
  • 10
  • 20
  • 2
    `HttpClient.post` returns an `Observable`. Please refer to the [official guide](https://angular.io/guide/http). – Jeto Oct 16 '18 at 19:02
  • Possible duplicate of [How do I return the response from an Observable/http/async call in angular2?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – ConnorsFan Oct 16 '18 at 19:04
  • The `login` method should return the Observable. You then subscribe to it in `onClick` and do all the processing inside of the callback. – ConnorsFan Oct 16 '18 at 19:07

1 Answers1

3

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));
}
Sunil Singh
  • 11,001
  • 2
  • 27
  • 48
  • is there a way to do it without using a callback? – Steinfeld Oct 16 '18 at 19:30
  • Thats how asynchronous call works. What is the issue you see with callback ? – Sunil Singh Oct 16 '18 at 19:32
  • @Steinfeild You could call `toPromise()` on the returning Observable and then use `async`/`await`. But I would suggest working with Observables as most Angular code is based around it. – Jeto Oct 16 '18 at 19:53