Ctfrancia
Ctfrancia

Reputation: 1588

In Angular Typescript how to create a Observable from Map()

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!

Upvotes: 0

Views: 1028

Answers (1)

matthiasunt
matthiasunt

Reputation: 719

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.

Upvotes: 1

Related Questions