【问题标题】:Angular cast json string to typed arrayAngular 将 json 字符串转换为类型化数组
【发布时间】:2019-09-19 14:28:22
【问题描述】:

SampleDataController:

[HttpGet("GetAllItems")]
public async Task<IActionResult> GetAllItems()
{
    return Json(await _storeContext.Table.AsQueryable().ToListAsync());
}

数据服务:

export class DataService {

  constructor(private http: HttpClient) { }

  GetAllItems() {
    return this.http.get("https://localhost:44381/api/SampleData/GetAllItems");
  }
}

组件:

import { Component } from '@angular/core';
import { DataService } from '../store.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {

  public itemsList: Item[];

  constructor(private logger: DataService) {}

  GetItems() {
    this.logger.GetAllItems().subscribe(
      data => this.itemsList = <Item[]>JSON.parse(JSON.stringify(data))
    )
  }
}

export interface Item {
  Id: number;
  Name: string;
  Surname: string;
}

组件html:

<button mat-button (click)="GetItems()">GetItems!</button>

<li *ngFor="let item of itemsList">
  <span>
    <br />
    {{item.Name}}
    <br />
    {{item.Surname}}
  </span>
</li>

点击按钮GetItems() 后返回对象数组。我认为data =&gt; this.itemsList = &lt;Items[]&gt;JSON.parse(JSON.stringify(data)) 应该转换为Item 的数组,我应该得到Item[] 数组。在 TypeScript 中将 json 转换为类型化数组的正确方法是什么?

Json 数据示例:

[
    {
        "id": 3,
        "name": "1",
        "surname": "2         "
    },
    {
        "id": 4,
        "name": "1",
        "surname": "2         "
    },
    {
        "id": 5,
        "name": "1",
        "surname": "2         "
    },

【问题讨论】:

    标签: c# json angular asp.net-core


    【解决方案1】:

    键入 HTTP 请求

    export class DataService {
    
      constructor(private http: HttpClient) { }
    
      GetAllItems(): Observable<Item[]> {
        return this.http.get<Item[]>("https://localhost:44381/api/SampleData/GetAllItems");
      }
    }
    

    然后做

    import { Component } from '@angular/core';
    import { DataService } from '../store.service';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    
        export class AppComponent {
    
          public itemsList: Item[];
    
          constructor(private logger: DataService) {}
    
          GetItems() {
            this.logger.GetAllItems().subscribe(
              (data: Item[]) => this.itemsList = data
            )
          }
        }
    
    export interface Item {
      Id: number;
      Name: string;
      Surname: string;
    }
    

    无论如何,还有一些进一步的建议。请使用通用命名规则,方法和成员使用 lowerCamelCase。还要避免订阅(改用异步管道)或至少取消订阅。

    【讨论】:

      【解决方案2】:

      使用Ok 方法而不是Json 来返回序列化对象,因为它的功能更完整:

      [HttpGet("GetAllItems")]
      public async Task<IActionResult> GetAllItems()
      {
          return this.Ok(await _storeContext.Table.AsQueryable().ToListAsync());
      }
      

      在角度方面,默认情况下,响应正文假定包含 JSON,因此您可以将您的服务改造成以下as explained in the docs

      export class DataService {
      
        constructor(private http: HttpClient) { }
      
        GetAllItems(): Observable<Item[]> {
          return this.http.get<Item[]>("https://localhost:44381/api/SampleData/GetAllItems");
        }
      }
      

      因此,您不需要手动反序列化任何内容(例如:使用 JSON.parse),因为 Angular 会处理这一步。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-10-13
        • 1970-01-01
        • 1970-01-01
        • 2019-02-09
        • 2020-04-27
        • 2013-03-14
        • 1970-01-01
        相关资源
        最近更新 更多