I'm getting this error, after I added a function called ngInit which will call the getCountries function in the Service class:
"Type 'Object' is not assignable to type '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;
});
}
}
Because of your
countryData = nullproperty initialization, TypeScript infers the type ofcountryDatato benull. Assigning anything other thannullto this property will result in the error you're seeing.To fix, you can:
Type the property as
any:Define a type for your data, and set the property to be either that type or
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
undefinedinstead ofnull):