Home > Net >  Observable is getting a not assignable to null error
Observable is getting a not assignable to null error

Time:12-21

I have this error :

error TS2322: Type 'Observable<any[]>' is not assignable to type 'null'.

For this code :

import { Component, OnInit } from '@angular/core';
import {HttpClient} from "@angular/common/http";

@Component({
  selector: 'app-articles',
  templateUrl: './articles.component.html',
  styleUrls: ['./articles.component.css']
})
export class ArticlesComponent implements OnInit {
  articles$ = null;
  constructor(private httpClient: HttpClient) { }

  ngOnInit(): void {
    // @ts-ignore
    this.articles$ = this.httpClient.get<any[]>('http://localhost:3000/articles');
  }

}

I added : // @ts-ignore so it can bypass the error and print me my database content.

But of course it's a temporary solution, i'd like to get rid of this error.

CodePudding user response:

The issue is that you set articles$ = null; which implies its type is null. To fix the type error you could do something like this

articles$: null | Observable<any[]> = null;

I prefere to do it like this. The ? tells the compile that it might be undefined

articles$?: Observable<any[]>; // type is: undefined | Observable<any[]>

CodePudding user response:

I believe the error is displaying as you have not defined the type of articles$

you can resolve this by just defining the type during the initial declaration like as follows.

 articles$:Observable<ArticleModel[]> = null;

Alternatively, you could just remove the initailly assigned null value.

  • Related