繁体   English   中英

如何将从 webapi 返回的自定义对象数组的 HttpResponse 响应分配给 typescript angular 中相同数组类型的 object?

[英]How to assign an HttpResponse response of custom array of objects returned from webapi to an object of same array type in typescript angular?

我第一次在 VSCODE 中使用 asp.net 内核和 angular,从视频教程中处理一个小项目。 下面是我的组件 typescript 文件 - index-actors.component.ts

    import { actorDTO } from './../actors.model';
import { ActorsService } from './../actors.service';
      import { Component, OnInit } from '@angular/core';
import { HttpResponse } from '@angular/common/http';

      @Component({
        selector: 'app-index-actors',
        templateUrl: './index-actors.component.html',
        styleUrls: ['./index-actors.component.css']
      })
      export class IndexActorsComponent implements OnInit {

        constructor(private actorService:ActorsService) { }
        actors!: actorDTO[];
        colunsToDisplay=['name','actions'];
        totalAmountOfRecords: string | null | undefined;
        currentPage=1;
        pageSize=5;
        ngOnInit(): void {
          this.actorService.get().subscribe((response:HttpResponse<actorDTO[]>)=>{
          this.actors=response.body;
          this.totalAmountOfRecords=response.headers.get("totalAmountOfRecords");
          });
        }

        delete(id:number){

        }

      }

我在生产线上遇到错误

this.actors=response.body;

错误说

错误:键入'actorDTO[] | null' 不能分配给类型 'actorDTO[]'。 类型“null”不能分配给类型“actorDTO[]”。 21 this.actors=response.body;

我似乎无法弄清楚如何解决这个问题。 为什么可以将具有actorDTO []数组的响应体直接分配给本身就是actorDTO数组的actor?

tsconfig.json

    /* To learn more about this file see: https://angular.io/config/tsconfig. */
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2017",
    "module": "es2020",
    "lib": [
      "es2018",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}

演员.services.ts

      import { observable, Observable } from 'rxjs';
  import { environment } from './../../environments/environment';
  import { HttpClient } from '@angular/common/http';
  import { actorCreationDTO, actorDTO } from './actors.model';
  import { Injectable } from '@angular/core';
  import { formatDateFormData } from '../utilities/utils';

  @Injectable({
    providedIn: 'root'
  })
  export class ActorsService {

    constructor(private http:HttpClient) { }
    private apiURL=environment.apiURL+"/actors";

    get(): Observable<any>{
    return this.http.get<actorDTO[]>(this.apiURL, {observe:'response'});
    }
    create(actor: actorCreationDTO){
      const formData= this.buildFormData(actor);
      return this.http.post(this.apiURL,formData);
      }
    private buildFormData(actor:actorCreationDTO) : FormData{
      const formData=new FormData();
      formData.append('name',actor.name);
      if(actor.biography){
        formData.append('biography',actor.biography);
      }
      if(actor.dateOfBirth){
        formData.append('dateOfBirth',formatDateFormData(actor.dateOfBirth));
      }
      if(actor.picture){
        formData.append('picture',actor.picture);
      }
  return formData;
    }
  }

尝试删除strict: true ,请在https://www.typescriptlang.org/tsconfig阅读更多相关信息。 这个设置为false的选项strict迫使你把! 在 class 中声明属性时,老实说有时很烦人。 :)

还可以考虑添加strictNullCheks: false

更多选项是this.actors = response.body || [] this.actors = response.body || []

在您的 tsconfig 中,默认设置了严格类型。 如果您查看HttpResponse的 Angular 文档,则body类型为T | null T | null 所以响应体可能是actorDTO[] | null actorDTO[] | null

由于设置了严格类型,您需要考虑响应正文中潜在的 null 情况。

选项1

输入您的 actor 属性以说明null

// IndexActorComponent
actors!: actorDTO[] | null;

选项 2

使用|| 如果响应正文是 null,则分配一个空数组。 使用这种用法可以让你的演员输入为actors:: actorDTO[]

this.actors = response?.body || [];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM