使用多个嵌套对象Angular初始化接口的简便方法

我有一个包含多个嵌套对象的接口,并且希望有一种更简单的方法来初始化它们。

目前我的界面

export interface Order {
  _id: string;
  orderDetails: {
    create_time: string;
    id: string;
    payer: {
      address: {
        country_code: string;
      };
      email_address: string;
      name: {
        given_name: string;
        surname: string;
      };
      payer_id: string;
    };
    purchase_units: [
      {
        amount: {
          value: string;
          currency_code: string;
        };
        payee: {
          email_address: string;
          merchant_id: string;
        };
        shipping: {
          address: {
            address_line_1: string;
            address_line_2: string;
            admin_area_1: string;
            admin_area_2: string;
            country_code: string;
            postal_code: string;
          },
          name: {
            full_name: string
          }
        };
      }
    ]
  };
  products: [
    {
      quantity: number
      _id: string,
      product: {
        _id: string,
        amount: number,
        category: string,
        description: string,
        imageUrls: [],
        title: string,
        userId: string
      }
    }
  ];
  user: {
    name: string,
    userId: string
  };
}

然后我像这样收到他们

export class AllOrdersComponent implements OnInit {
  order: Order = {orderDetails: {payer:{name: {} as any}as any} as any} as any;
  id: string;
  constructor(
    private route: ActivatedRoute,
    private adminService: AdminService
  ) {}

  ngOnInit() {
    this.route.params.subscribe((params: Params) => {
      this.id = params["id"];
      this.adminService.getOrder(this.id)
     .subscribe(orderData => {
       this.order = orderData.order;
     })
    });
  }
}

如果我在执行OnInit函数中的http请求之前没有初始化它们,则会出现问题,我得到一个错误消息,即'_co.order.orderDetails'未定义。

所以我像在组件开头一样初始化它们,但是看起来很冗长和多余,必须有一种更漂亮,更容易的方法来执行此操作?

评论
  • 不爱请闪开
    不爱请闪开 回复

    问题不在于对象的结构。当等待异步数据时,您想在任何地方使用它,都必须检查是否定义了变量。不要让自己成为一个空的对象。在获取实际数据之前,请保持未定义状态。

    因此,在您的HTML中,您可以使用

    <div *ngIf="order">
      <span>{{ order.orderDetails.payer.email_address }}</span>
    </div>
    

    同样,在定义接口时,出于方便的考虑,您可以创建子对象的接口:

    export interface Order {
      _id: string;
      orderDetails: OrderDetails;
      products: Products[];
      user: User;
    }