【问题标题】:Save response to "variable" angular保存对“可变”角度的响应
【发布时间】: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,但我没有任何问题..

标签: angular response


【解决方案1】:

不知道保存整个内容并像您编写的函数一样访问是什么意思。如果您的要求是在不再次调用的情况下从 api 响应中获取值,则可以在使用 this.LAUNCHRESPONSE 设置 api 响应后为其使用 getter 函数。

您的服务将如下所示:

  LAUNCHRESPONSE: launchResponseObject[] = [];

  async getData() {

    try {
      this.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)}`);
    }
  }

getStoredResponseData(){
  return this.LAUNCHRESPONSE;
}

您可以稍后调用服务内部声明的getStoredResponseData()来获取响应详细信息。

【讨论】:

  • 这不起作用,因为当我尝试这样做时,我得到:“launchResponseObject”类型缺少“launchResponseObject[]”类型中的以下属性:长度、弹出、推送、连接和 26更多。
  • 您确定从 API 返回的是一组 launchResponseObjects..?您现在遇到的问题是您输入的内容不一致。将 .get 更改为 .get 或将 LAUNCHRESPONSE:launchResponseObject[] = [] 更改为 LAUNCHRESPONSE:launchResponseObject = {}
  • 我在响应中得到的不是数组而是对象,是的。我回来后会尝试,但我想我已经尝试过了。会回来报告的。
  • 这确实有效,但我不得不稍微修改一下代码,包括界面。谢谢!
  • 所以您面临的主要问题是数据类型。
猜你喜欢
  • 2019-02-06
  • 1970-01-01
  • 2016-09-04
  • 2020-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多