0
votes

I have a contact service that is responsible for managing contacts, in a address book, type of way. for example my interface looks like this:

export interface AddressBook {
  a?: Contact[];
  //...
}

and Contact[] is just stuff like name, age, email. In my service I currently have this implementation:

  private addressBook: Map<string, Contact[]> = new Map<string, Contact[]>();
  private readonly ab$: BehaviorSubject<string | Contact[]> = new BehaviorSubject<string | Contact[]>(this.addressBook);

  public constructor(){}

  public getContacts(): Observable<string | Contact[]> {
    return this.ab$.asObservable();
  }

however the problem that I am getting is with the private readonly ab$: BehaviorSubject<string | Contact[]> = new BehaviorSubject<string | Contact[]>(this.addressBook) where it says:

not assignable to parameter of type 'string | Contact[]'. Type 'Map' is missing the following properties from type 'Contact[]': length, pop, push, concat, and 21 more.ts(2345)

I cannot see where this error is coming from. Thank you guys for any help!

1
Do not do this new BehaviorSubject(this.addressBook). You will trigger this expression has changed errors in Angular, and it is also an anti-pattern in functional programming. - Reactgular
what would be the better way to do this? the articles that I have read have the new BehaviorSubject(this.addressBook) - Ctfrancia
@Ctfrancia maybe you can leave out the whole BehaviorSubject part and directly access the addressBook. - robert
Alright, I'll take a look at that @robert - Ctfrancia

1 Answers

1
votes

Your BehaviourSubject should be instantiated as follows:

private readonly ab$: BehaviorSubject<Map<string, Contact[]>> = new BehaviorSubject(new Map({}));

Since it has to be same type as addressBook.