Surya
Surya

Reputation: 754

code inside angular subscribe not waiting for API response to come

Code inside angular subscribe not waiting for API response to complete? Is it waiting for only API response status code not the actual response value?

I have an API which generally gives RSA public key (string) in response. I am calling the API from Angular (version 8) ts file.

//For fetching public key from API response 
    this.authService.publicKeyGen(identifier).subscribe(
            res => {
              console.log("fooooo...");   NOT PRINTING / NOT EXECUTING
              pubKey = res;
            },
              (e => console.log('error: ', e)),
              (() => console.log('the sequence completed!'))  PRINTING / EXECUTING
            );

    public publicKeyGen(identifier) {
        let url = this.authUrl + "/v1/keys/generate";
        return this.http.get(url, {
          params: { identifier : identifier}
        });
      }

Though the API call is success (status code 200) but it is not going inside the "res" and I am not able to get the response value.

Note: Actually the API returns success code 200 first and then after a small delay it is giving the response data. Inside the subscribe, I am not able to set the public key from response value as API call gets success (200) but the API response data still not available and not executing the "res" part though it is going inside the subscribe as API status code already came.

Please help.

API Response - MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDTqMCDom4QjKFoucN/Wa5CJ+eECcs2Q7V5uAWH4DUc1F3+02LsWOwWP5JKVLKOEBjybR50eKpGLsTwnIUNeh8oRsq7l4YAaeYDSrbkij62m8tsPyMwleeD3jIc8RlAD7Zt/bTvJGMA/W6hJJ0wf0kU2pmPuauGBIdeZqoYhRNCqwIDAQAB

Upvotes: 0

Views: 1369

Answers (2)

Ganesh
Ganesh

Reputation: 6016

Try to set the responseType for headers to verify it's response type from server.

 public publicKeyGen(identifier) {
    let url = this.authUrl + "/v1/keys/generate";
    const headers = new HttpHeaders().set('Content-Type', 'text/plain'); 
    return this.http.get(url, { headers, responseType: 'text'});
 }

If it's plain string then console log will print. You can convert it to JSON by using parse method like below

const pubKey = JSON.parse(res);

Happy Coding.. :)

Upvotes: 1

Yoni A
Yoni A

Reputation: 124

Is your publicKeyGen method reside in auth.service.ts file?

Also, better to add the return value to publicKeyGen signature, like so:

public publicKeyGen(identifier): Observable<string> {
    let url = this.authUrl + "/v1/keys/generate";
    return this.http.get(url, {
      params: { identifier : identifier}
    });
  }

Upvotes: 1

Related Questions