-1

This is perhaps a silly question but I couldn't find an explanation anywhere else.

In the Angular official tutorial of routing, the following array is provided:

export const products = [
  {
    name: 'Phone XL',
    price: 799,
    description: 'A large phone with one of the best screens'
  },
  {
    name: 'Phone Mini',
    price: 699,
    description: 'A great phone with one of the best cameras'
  },
  {
    name: 'Phone Standard',
    price: 299,
    description: ''
  }
];

In the routing section, when displaying a single product details, the following syntax is used to get the current product index through the URL:

this.product = products[+params.get('protectId')];

I noticed that without the '+', the params return null. Could anyone explain to me whats the purpose of the +?

Dragolis
  • 66
  • 1
  • 7

2 Answers2

3

From Angular Docs on ParamMap

get()

Retrieves a single value for a parameter.

Returns:

string | null: The parameter's single value, or the first value if the parameter has multiple values, or null when there is no such parameter.

That would mean that params.get('protectId') would return a string.

The + only converts the string into a number. That's all there is to it :)

Community
  • 1
  • 1
SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
0

params.get('protectId') returns the ID as a string, the + typecasts it to an int (or number).

This is necessary since the array is indexed with numbers 0, 1, 2 and so on and not by '0', '1'.

Hence products[+params.get('protectId')] only works when you've typecasted it to an int. To confirm, you can do it as: products[Number(params.get('protectId'))] and get the same result

Yash Shah
  • 131
  • 5