import {Injectable} from '@angular/core';
import {BehaviorSubject, Observable, Subject} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ModalService {
private display: BehaviorSubject<'open' | 'close'> = new BehaviorSubject('close');
watch(): Observable<'open' | 'close'> {
return this.display.asObservable();
}
open() {
this.display.next('open');
}
close() {
this.display.next('close');
}
}
Error: src/app/services/modal.service.ts:9:11 - error TS2322: Type 'BehaviorSubject<"close">' is not assignable to type 'BehaviorSubject<"open" | "close">'. Types of property 'observers' are incompatible. Type 'Observer<"close">[]' is not assignable to type 'Observer<"open" | "close">[]'. Type 'Observer<"close">' is not assignable to type 'Observer<"open" | "close">'. Type '"open" | "close"' is not assignable to type '"close"'. Type '"open"' is not assignable to type '"close"'.
https://betterprogramming.pub/create-a-modal-for-your-angular-app-without-libs-671bd7280867
This article shows Modal working in Angular but I am having trouble with this.
CodePudding user response:
It is a type validation issue
change
private display: BehaviorSubject<'open' | 'close'> = new BehaviorSubject('close');
to
private display: BehaviorSubject<'open' | 'close'> = new BehaviorSubject<'open' | 'close'>('close');
and all will be aligned.
CodePudding user response:
Try this:
private display = new BehaviorSubject<'open' | 'close'>('close');
Basically what Fabio said is right, but you might as well let Typescript infer the type. Defining it twice is redundant.