首页 > 解决方案 > 如何在Angular中为对象赋值

问题描述

我有一个 RestApi,它以 Json 格式向我发送响应,该响应具有例如一个地址对象,然后保存地址 1、地址 2、城市等。所以我在我的应用程序中创建了一个接口,其中包含这些对象的定义,例如

export interface ISurveyResponseDetail {
  docID?: string;
  permission?: string;
  property?: IProperty;
  surveyID?: string;
}
export interface IProperty {
  address1?: string;
  address2?: string;
  city?: string;
  state?: string;
  zip?: string;

然后在我的 ts 文件中,我想使用数据适配器将我的响应映射到这个接口。但我不确定我将如何将 IProperty 类型的属性对象然后能够分配值

static adaptSurveyResponseDetail(data): ISurveyResponseDetail {
        if (data) {
            return {
                property:
                // address1 _.get(data, 'property.address1', null),
                // city _.get(data, 'property.city', null),
                docID: _.get(data, 'docID', null),
                permission: _.get(data, 'permission', null),
                surveyID: _.get(data, 'survey_id', null),
              };
            } else {
            return data;
        }

    }

标签: angulartypescript

解决方案


尝试这样的事情

static adaptSurveyResponseDetail(data): ISurveyResponseDetail {
    if (data) {
      return {
        property: {
          address1: data.address1,
          address2: data.address2,
          city: data.city,
          state: data.state,
          zip: data.zip,
        },
        docID: data.docID,
        permission: data.permission,
        surveyID: data['survey_id'],
      };
    } else {
      return data;
    }
  }

推荐阅读