Angular - Argument of type 'ISiteInfo | null' is not assignable to parameter of type 'ISiteInfo | undefined'

Viewed 340

In my Angular-12 application, I have this model interface:

export interface ISiteInfo {
  id: number;
  name: string;
  email: string;
}

And also this service:

import {ISiteInfo} from '../models/site-info.model';

export class SiteInfoService {

  private infoSiteSource = new BehaviorSubject < ISiteInfo | null > (null);
  infoSite = this.infoSiteSource.asObservable();

  setInfoSite(data: ISiteInfo) {
    this.infoSiteSource.next(data);
  }

  constructor(
    private http: HttpClient,
    private api: ApiService,
  ) {}

  public get(refresh: boolean = false): Observable < ISiteInfo > {
    return new Observable(observer => {
      if (!refresh && this.infoSiteSource.getValue()) {
        observer.next(this.infoSiteSource.getValue());
        return observer.complete();
      }
      this.http.get < ISiteInfo > (this.api.baseURL + '/GInfoSite').subscribe(value => {
        this.setInfoSite(value);
        observer.next(this.infoSiteSource.getValue());
        observer.complete();
      });
    });
  }
}

I got this error:

Argument of type 'ISiteInfo | null' is not assignable to parameter of type 'ISiteInfo | undefined'. Type 'null' is not assignable to type 'ISiteInfo | undefined'.ts(2345)

And this line highlighted:

this.infoSiteSource.getValue()

in

observer.next(this.infoSiteSource.getValue());

Also, when I removed |null from:

private infoSiteSource = new BehaviorSubject(null);

the error changed to:

Argument of type 'null' is not assignable to parameter of type 'ISiteInfo'.ts(2345)

How do I get this sorted out?

Thanks

2 Answers

Does it change anything if you try this:

private infoSiteSource = new BehaviorSubject < ISiteInfo | undefined > (undefined);

Also, it looks like your get method is supporting a refresh option. I've often done a refresh feature using another Observable, something like this:

  // To support a refresh feature
  private refresh = new BehaviorSubject<boolean>(true);

  products$ = this.refresh
    .pipe(
      mergeMap(() => this.http.get<Product[]>(this.productsUrl)
        .pipe(
          tap(data => console.log('Products', JSON.stringify(data))),
          catchError(this.handleError)
        )
      ));

(And to the person who will no doubt edit this post ... hope you get lots of SO points for editing out this "hope this helps"!)

private infoSiteSource = new BehaviorSubject < ISiteInfo | any> (null);

Related