0

I am trying to set values in a Map in angular. An I try to set the values when I click some particular buttons and invoke the onClick function

typeArray: Map<number,string>;

  Rent(movieId: number){
    this.typeArray.set(movieId,"Rental");
    console.log(this.typeArray.get(movieId));
  }
  Purchase(movieId: number){
    this.typeArray.set(movieId,"Purchased");
    console.log(this.typeArray.get(movieId));
  }

But I am getting this error

core.js:4197 ERROR TypeError: Cannot read property 'set' of undefined
at CartComponent.Purchase (cart.component.ts:77)
at CartComponent_tr_23_Template_button_click_13_listener (cart.component.html:34)
at executeListenerWithErrorHandling (core.js:14310)
at wrapListenerIn_markDirtyAndPreventDefault (core.js:14345)
at HTMLButtonElement.<anonymous> (platform-browser.js:582)
at ZoneDelegate.invokeTask (zone-evergreen.js:399)
at Object.onInvokeTask (core.js:27418)
at ZoneDelegate.invokeTask (zone-evergreen.js:398)
at Zone.runTask (zone-evergreen.js:167)
at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:480)
1
  • Try using arrow functions intead Commented Oct 6, 2020 at 16:10

2 Answers 2

1
typeArray: Map<number,string>;

This just declares the property to be a Map but doesn't create it. So, the value of this Map type property remains 'undefined'.

For creating a Map you will have to call its constructor like

typeArray: Map<number, string> = new Map<number, string>();

Now its value is not undefined and the set and get methods become available for use.

Sign up to request clarification or add additional context in comments.

Comments

0

You only declare the Map, but you don't create it, try this:

typeArray = new Map<number,string>();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.