类型“Object”不可分配给类型“null”

0 typescript ng-init angular angular12

在添加一个名为的函数后,我收到此错误,ngInit该函数将调用类getCountries中的函数Service

“类型‘Object’不能分配给类型‘null’”

import { Component, OnInit } from '@angular/core';
import {MessageService} from './message.service';

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

  title = 'Tour of Heroes';

  countryData = null;
  constructor(private api:MessageService) {}
  ngOnInit() {
    this.api.getCountries().subscribe((data)=>{
      this.countryData = data;
    });
  }

}
Run Code Online (Sandbox Code Playgroud)

Rob*_*sen 5

由于属性初始化,TypeScript 推断出to becountryData = null的类型。分配除此属性以外的任何内容都会导致您看到的错误。countryDatanullnull

要修复,您可以:

  1. 将属性键入为any

    countryData: any = null;
    
    Run Code Online (Sandbox Code Playgroud)
  2. 为您的数据定义一个类型,并将属性设置为该类型或null

    countryData: CountryDataType | null = null;
    
    Run Code Online (Sandbox Code Playgroud)
  3. 为数据定义一个类型,将属性设置为该类型,并将其标记为可选(请注意,在这种情况下,初始值不是undefinednull

    countryData?: CountryDataType;
    
    Run Code Online (Sandbox Code Playgroud)