如何在Angular中声明JSOn对象 | Typescript例子

340 阅读3分钟

Angular declare json object

本教程解释了在Angular中声明和初始化JSOn对象数据的多种方法。它还包括一个Typescript的例子。

有时,你想在Angular中声明JSOn对象,JSOn对象可以包含String、boolean、原始值的数字,以及嵌套对象的Array。

有多种方法来声明一个jSOn对象。

让我们看看如何创建和初始化一个json对象的数组。

如何用Angular声明任何类型的json对象?

Typescript是一种类型化的语言,用于在编译时进行类型检查。所以在Angular中,每个变量都必须持有一个类型,以指定类型的类型。

JSOn是正常的数据,所以为any 类型声明一个变量。Typecript中的任何类型能够接受任何类型的数据。

在下面的例子中,JSOn对象的数组在Angular组件中被创建和初始化。

声明一个JSOn对象的变量,并在构造函数中把一个json对象的数组投给这个变量。

下面是一段代码,angular any type json variable create example

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-array-json-dates',
  templateUrl: './array-json-dates.component.html',
  styleUrls: ['./array-json-dates.component.scss']
})
export class ArrayJsonDatesComponent implements OnInit {
  jsonObject: JSON;

  arrayObj: any = [
    {
      id: 1,
      name: "john",
      lastModified: '2011-01-01 02:00:00'
    },
    {
      id: 2,
      name: "Franc",
      lastModified: '2001-01-01 02:00:00'
    },
    {
      id: 3,
      name: "Andrew",
      lastModified: '2021-01-01 02:00:00'
    },
    {
      id: 11,
      name: "Mark",
      lastModified: '2020-01-01 02:00:00'
    },
    {
      id: 12,
      name: "Eric",
      lastModified: '2020-02-01 02:00:00'
    },
    {
      id: 8,
      name: "Tony",
      lastModified: '1990-01-01 02:00:00'
    }
  ]

  constructor() {
    this.jsonObject = this.arrayObj;

  }

  ngOnInit(): void {

  
}

这种方法很简单,容易声明和初始化json对象。这种方法的缺点是json数据的验证在编译类型时没有被检查。

如何使用Angular中的接口声明JSON对象

在这种方法中,使用json格式的数据创建一个接口 让我们在Angular中声明一个接口

interface Employee {
    id: number;
    name: string;
    salary: number
}

在Angular组件中,声明一个Employee数组的变量并分配json对象。

一个例子

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-array-json-dates',
  templateUrl: './array-json-dates.component.html',
  styleUrls: ['./array-json-dates.component.scss']
})
export class ArrayJsonDatesComponent implements OnInit {

  arrayJson: Employee[] = [
    {
      id: 1,
      name: "john",
      salary: 5000
    },
    {
      id: 11,
      name: "eric",
      salary: 15000
    }

  ]
  empObject = {
    id: 8,
    name: "Tony",
    salary: 5000
  };
  constructor() {

  }

  ngOnInit(): void {

  }
  
}

如何在typescript中为JSON对象创建和初始化一个类型?

type 关键字允许在typecript中声明和分配新的类型。你可以查看更多关于[typescript type](/typescript-type-keyword/

JSON持有字符串键,值可以是字符串、数字、布尔值和数组。

让我们声明新的类型JsonObjectType

type JsonObjectType =
    | string
    | number
    | boolean
    | { [x: string]: JsonObjectType }
    | Array;

JsonObjectType允许在json对象中存储普通的、嵌套的和数组的内容。

在下面,创建了一个JsonObjectType 类型的变量,并将其分配给JSOn对象,如下所示

const jsonData: JsonObjectType= [
    {
      id: 1,
      name: "john",
      salary: 5000
    },
    {
      id: 11,
      name: "eric",
      salary: 15000
    }
  ]

Type 关键字在Angular组件中工作。

总结

在本教程中,你学到了比较两个相等的日期以及比较未来和给定日期与当前日期的不同例子。