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)
由于属性初始化,TypeScript 推断出to becountryData = null
的类型。分配除此属性以外的任何内容都会导致您看到的错误。countryData
null
null
要修复,您可以:
将属性键入为any
:
countryData: any = null;
Run Code Online (Sandbox Code Playgroud)
为您的数据定义一个类型,并将属性设置为该类型或null
:
countryData: CountryDataType | null = null;
Run Code Online (Sandbox Code Playgroud)
为数据定义一个类型,将属性设置为该类型,并将其标记为可选(请注意,在这种情况下,初始值不是undefined
)null
:
countryData?: CountryDataType;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5148 次 |
最近记录: |