Im getting this "Type 'Object' is not assignable to type 'null'" error ,after i added a function called ngInit which will call the getCountries function in the Service class.
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;
});
}
}
CodePudding user response:
Because of your countryData = null
property initialization, TypeScript infers the type of countryData
to be null
. Assigning anything other than null
to this property will result in the error you're seeing.
To fix, you can:
Type the property as
any
:countryData: any = null;
Define a type for your data, and set the property to be either that type or
null
:countryData: CountryDataType | null = null;
Define a type for your data, set the property to be of that type, and mark it as optional (note that in this case the initial value is
undefined
instead ofnull
):countryData?: CountryDataType;
CodePudding user response:
You have declare the return type as null or turn off strictNullChecks in your tsconfig.
Change the type null as any.
CodePudding user response:
simple change to make it work is to change the type to any or provide a interface for country
countryData: any;
or as Robby
countryData:CountryDateType