6

i want to make a function that returns a token from a server but http.post() gets a response after my function returned the token.

How do i wait for http.post() before returning the token.

My code:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()

export class ServerConnectionService{
    constructor( private http : Http) { }
    token : string;
    Login(Password : string, Username : string, ServerRootURL : string) : string
    {
        let url = ServerRootURL + "api/AdminApp/RegisterToken";
        this.http.post(url, { "Username": Username, "Password": Password }).toPromise()
            .then(res => this.token =  res.json())
            .catch(msg => console.log('Error: ' + msg.status + ' ' + msg.statusText))
        return this.token;
    }
}

Thank you in advance.

2 Answers 2

4

Actually you can't wait to a asynchronous code and return something from it.As you use promise, you need to use thenable functions and write the rest logic which is related to the result of it in that thenable functions. In your case it will be

Login(Password : string, Username : string, ServerRootURL : string): Promise<string>  {
      let url = ServerRootURL + "api/AdminApp/RegisterToken";
      return this.http.post(url, { "Username": Username, "Password": Password }).toPromise()
                      .then(res => this.token =  res.json())
                      .catch(msg => console.log('Error: ' + msg.status + ' ' + msg.statusText))
 }

and you need to use it like

Login('password', 'username', 'http://localhost:8081').then(token => your logic here)
Sign up to request clarification or add additional context in comments.

Comments

4

You can define your Login() function as async. Then you may await your http.post() call:

public async Login(pass: string, user: string): string {
    ...
    let response: Response = await this.http.post(url, data).toPromise();
    return response.json();
}

Note that calling Login() will also need to be awaited.

let token = await Login("foo", "bar");

2 Comments

Mention also that await must be also in the async function
.toPromise() is deprecated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.