1

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;
    }
  }
2
  • Can you please post your tsconfig.json file? Commented Dec 18, 2021 at 20:59
  • Strict typing is set in your tsconfig. In your component if you put actors!: actorDTO[] | null the error should go away. Commented Dec 18, 2021 at 21:24

2 Answers 2

1

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 || [];

Sign up to request clarification or add additional context in comments.

Comments

0

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 || [];

2 Comments

I am new to typescipt as well. What is the usual standard value strict typing in a development environment? Should it be removed or set to false?
Since Angular 11 strict is enabled by default on all new projects. Strict mode adds extra type safety features to your project. It's a personal choice if you want to use it or not. I believe it's recommend to keep enabled but is not mandatory. Check my edit for links to a couple articles about strict mode.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.