Home > OS >  How to assign an HttpResponse response of custom array of objects returned from webapi to an object
How to assign an HttpResponse response of custom array of objects returned from webapi to an object

Time:12-19

I am using asp.net core with angular in VSCODE for the first time, working on a small project from video tutorial. Below is my component typescript file - 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){

        }

      }

I am getting an error at the line

this.actors=response.body;

The error says

Error: Type 'actorDTO[] | null' is not assignable to type 'actorDTO[]'. Type 'null' is not assignable to type 'actorDTO[]'. 21 this.actors=response.body;

I can't seem to figure out how to fix this issue. Why can a response body which has an array of actorDTO[] be assigned directly to actors which is itself an array of actorDTO?

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
  }
}

actors.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;
    }
  }

CodePudding user response:

Try removing strict: true and please read more about it at https://www.typescriptlang.org/tsconfig. This option strict that is set to false is forcing you to put ! when declaring a property in a class and to be honest is sometimes annoying. :)

Also consider adding strictNullCheks: false to your tsconfig.json.

On more option that will maybe work is this this.actors = response.body || [];

CodePudding user response:

In your tsconfig strict typing is set by default. If you look at the Angular doc for HttpResponse the type of body is T | null. So the response body could potentially be actorDTO[] | null.

Since strict typing is set, you need to account for the potential null case in the response body.

Option 1

Type your actors property to account for null.

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

Option 2

Use the || to assign an empty array if the response body is null. With this use can keep you actors typed as actors!: actorDTO[].

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