angular subscribe 中的代码不等待 API 响应完成?是否只等待 API 响应状态码而不是实际响应值?
我有一个 API,它通常会提供 RSA 公钥(字符串)作为响应。我正在从 Angular(版本 8)ts 文件调用 API。
//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}
});
}
虽然 API 调用成功(状态代码 200),但它没有进入“res”,我无法获得响应值。
注意:实际上 API 首先返回成功代码 200,然后在一小段延迟后给出响应数据。在订阅内部,当 API 调用成功 (200) 时,我无法从响应值设置公钥,但 API 响应数据仍然不可用并且不执行“res”部分,尽管它作为 API 状态进入订阅内部代码已经来了。
请帮忙。
API 响应 - MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDTqMCDom4QjKFoucN / Wa5CJ + eECcs2Q7V5uAWH4DUc1F3 + 02LsWOwWP5JKVLKOEBjybR50eKpGLsTwnIUNeh8oRsq7l4YAaeYDSrbkij62m8tsPyMwleeD3jIc8RlAD7Zt / bTvJGMA / W6hJJ0wf0kU2pmPuauGBIdeZqoYhRNCqwIDAQAB
答案 0 :(得分:1)
您的 publicKeyGen
方法是否驻留在 auth.service.ts
文件中?
此外,最好将返回值添加到 publicKeyGen
签名中,如下所示:
public publicKeyGen(identifier): Observable<string> {
let url = this.authUrl + "/v1/keys/generate";
return this.http.get(url, {
params: { identifier : identifier}
});
}
答案 1 :(得分:1)
尝试设置 headers 的 responseType 以验证它是来自服务器的响应类型。
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'});
}
如果它是纯字符串,则将打印控制台日志。您可以使用如下解析方法将其转换为 JSON
const pubKey = JSON.parse(res);
快乐编码.. :)