在我添加了一個名為 ngInit 的函式后,我得到了這個“型別‘物件’不可分配給型別‘空’”錯誤,該函式將呼叫服務類中的 getCountries 函式。
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;
});
}
}
uj5u.com熱心網友回復:
由于您的countryData = null屬性初始化,TypeScript 推斷出的型別countryData為null。分配除此屬性以外null的任何內容都會導致您看到的錯誤。
要修復,您可以:
鍵入屬性為
any:countryData: any = null;為您的資料定義一個型別,并將屬性設定為該型別或
null:countryData: CountryDataType | null = null;為您的資料定義一個型別,將屬性設定為該型別,并將其標記為可選(請注意,在這種情況下,初始值是
undefined而不是null):countryData?: CountryDataType;
uj5u.com熱心網友回復:
您已在 tsconfig 中將回傳型別宣告為 null 或關閉 strictNullChecks。
將型別 null 更改為 any。
uj5u.com熱心網友回復:
使其作業的簡單更改是將型別更改為 any 或為國家/地區提供介面
countryData: any;
或作為羅比
countryData:CountryDateType
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/493811.html
