【发布时间】:2021-07-17 18:14:32
【问题描述】:
如何将此响应保存到变量中,以便我可以从其他函数访问它?
代码:
export interface launchResponse {
status: number;
url: string;
token: string;
}
export interface launchResponseObject {
response: launchResponse;
}
然后在服务中:
LAUNCHRESPONSE: launchResponseObject[] = [];
async getData() {
try {
const LAUNCHRESPONSE = await this.http
.get<launchResponseObject>(
`${$apiUrl}`
)
.toPromise();
console.log(LAUNCHRESPONSE.response.url)
console.log(LAUNCHRESPONSE.response.token)
} catch (error) {
console.log(`Promise rejected with ${JSON.stringify(error)}`);
}
}
我知道我可以像这样保存它:this.url = LAUNCHRESPONSE.response.url 但我想保存整个内容,然后像在其他函数中一样访问它。
我也尝试过使用 this.LAUNCHRESPONSE 而不是 const LAUNCHRESPONSE,但没有成功。我知道这很愚蠢,但我不知道是什么。
【问题讨论】:
-
向我们展示您尝试过但不起作用的方法
-
例如,我尝试使用 this.LAUNCHRESPONSE 而不是 const LAUNCHRESPONSE,我得到:“launchResponseObject”类型缺少“launchResponseObject[]”类型中的以下属性:长度、弹出、推送、连接,还有 26 个。
-
您将变量声明为数组,但声明 API 调用以返回单个项目。你必须选择哪个是正确的并修复另一个。
-
API 肯定不会返回一个数组,而是一个包含更多对象的对象。如果我现在可以访问第一个对象就足够了。如何修复声明?我尝试了 LAUNCHRESPONSE = {} 位仍然无法使其工作..虽然我有一个返回对象数组的 api,但我没有任何问题..