Angular 2 is throwing an error that states, "The argument type 'number' cannot be assigned to a parameter type of 'string'"

Creating an angular2 application has been my recent project, utilizing the following API:

This particular API provides an array of dictionaries (here's a sample):

[
{
    "id": "bitcoin",     <------ The focus is on this ID
    "name": "Bitcoin", 
    "symbol": "BTC", 
    "rank": "1", 
    "price_usd": "9347.32", 
    "price_btc": "1.0", 
    "24h_volume_usd": "7926060000.0", 
    "market_cap_usd": "158936099373", 
    "available_supply": "17003387.0", 
    "total_supply": "17003387.0", 
    "max_supply": "21000000.0", 
    "percent_change_1h": "-0.24", 
    "percent_change_24h": "1.1", 
    "percent_change_7d": "6.62", 
    "last_updated": "1524926675"
}, 

To navigate to different pages, I implement routing parameters in this manner:

<tr *ngFor="let curr of currency" [routerLink]="['/currdetail',curr.id]">    <------ Here 
      <th scope="row">{{ curr.rank }}</th>
      <td>{{curr.name}}</td>
      <td>{{curr.symbol}}</td>
      <td>{{curr.market_cap_usd}}</td>
      <td>{{curr.price_usd}}</td>
      <td>{{curr.price_btc}} </td>
      <td>{{curr.available_supply}} </td>
      <td>{{curr['24h_volume_usd']}} </td>
      <td>{{curr.percent_change_1h}} </td>
      <td>{{curr.percent_change_24h}}</td>
      <td>{{curr.percent_change_7d}} </td>
    </tr>

I define the routes and include them in the routing module as follows:

export const routes: Routes = [
    { path: 'table',  component: TableComponent },
    { path: 'currdetail/:id',     component: CurrdetailComponent },
    { path: '', redirectTo: '/table', pathMatch: 'full' },
];

The structure of the Currdetail component is like this:

import { Component, OnInit } from '@angular/core';
import { CrypdataService } from '../crypdata.service'
import { Params, ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';

@Component({
  selector: 'app-currdetail',
  templateUrl: './currdetail.component.html',
  styleUrls: ['./currdetail.component.css'],
  providers: [CrypdataService],
})
export class CurrdetailComponent implements OnInit {

  private curr;

  constructor(private crypdataservice: CrypdataService, private route: ActivatedRoute, private location: Location) { }

  ngOnInit() {
  let id = +this.route.snapshot.params['id'];
  this.curr = this.crypdataservice.getcurr(id);
  }

  goBack(): void{
    this.location.back();
  }

}

Here are the contents of the crypdataservice file:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class CrypdataService {

  private baseUrl: string = 'https://api.coinmarketcap.com/v1/ticker/';

  constructor(private http: Http) { }

  getcurr(id : string){
      return this.http.get(`https://api.coinmarketcap.com/v1/ticker/`+id).map((res:Response) => res.json());
  }

  getall(){
      return this.http.get(`https://api.coinmarketcap.com/v1/ticker/`).map((res:Response) => res.json());
  }
}

A specific error message pops up:

ERROR in src/app/currdetail/currdetail.component.ts(20,44): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.

The issue arises from assigning a number as the ID without specification. Any insights would be appreciated. Thank you for your attention.

The intent is to utilize the API to retrieve details of a selected currency: <---- identified by this ID

Answer №1

To prevent TypeScript from interpreting the id as a number, modify your code and remove the + in the id declaration:

let id = this.route.snapshot.params['id'];

This adjustment will ensure that when you invoke getcurr(id), it won't be treated as a numeric value by TypeScript.

Unary plus (+) (docs)

The unary plus operator comes before its operand and results in the operand being evaluated but tries to convert it into a number, if necessary. While unary negation (-) can also change non-numeric values into numbers, using the unary plus is the fastest and recommended method for converting something into a numerical value. It specifically focuses on converting string representations of integers and floats, along with non-string values like true, false, and null. Both decimal and hexadecimal ("0x"-prefixed) integer formats are accepted. Negative numbers are supported (except for hex). If the conversion fails for a particular value, it will result in NaN.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Refresh causing Angular routing failure due to identical names for Angular route and server route

I've encountered an interesting issue with Angular (version 5) involving the setup of routes in my application. Here's how they are configured: {path: 'calendar', canActivate: [AuthGuard], component: ProjectsComponent } {path: 'm ...

Tips for accessing a route using query parameters without displaying special characters like '?' and '=' in the URL

I am new to Angular routing and I need help implementing it for navigating to a details page when an icon is clicked from the parent component. Below is my code snippet: product.component.ts // Method called when the edit icon is clicked loadSingleRec ...

Have the validation state classes (such as .has-error) been removed from Bootstrap 5?

I've noticed that the validation state classes (.has-success, .has-warning, etc) seem to have been removed in bootstrap 5 as they are not working anymore and I can't find them in the bootstrap.css file. Before, I could easily use these classes w ...

Incorporate TypeScript code into an Angular project by compiling it to NPM using Azure DevOps and adding it as a

I've been given a task that is completely outside of my area of expertise - using DevOps... What I need to do is transform a TypeScript library into an npm package, upload it to DevOps (as an artifact?), and include it as a dependency in an Angular ...

Utilize Javascript to compare nested objects and store the differences in a separate object

I have a dilemma involving two JavaScript objects var order1 = { sandwich: 'tuna', chips: true, drink: 'soda', order: 1, toppings: [{VendorNumber: 18, PreferredFlag: false, SupportedFlag: true}, {VendorNumber: 19, ...

Deploying AWS CDK in a CodePipeline and CodeBuild workflow

I am currently attempting to deploy an AWS CDK application on AWS CodePipeline using CodeBuild actions. While the build and deploy processes run smoothly locally (as expected), encountering an issue when running on CodeBuild where the cdk command fails w ...

Sending information to an Angular 2 Application via a form

What is the most effective way to submit a form to an Angular 2 application from a non-angular website? Simply setting the app as the action URL with method="GET" will not work, as Angular 2 utilizes "matrix URL notation" which means that the browser will ...

Having difficulty configuring my Angular .NET Core 2.1 web application correctly on GoDaddy

After deploying my netcore 2.1 Angular application using Visual Studio FTP profile to my Godaddy Host, I encountered a few issues. The deployment included the following contents: ClientApp folder wwwroot appsettings.json application.dlls web.config In t ...

PrimeNG - Sticky header feature malfunctioning in the p-table

Hello there, I am currently using PrimeNG p-table which features both horizontal and vertical scrolling. My goal is to implement a sticky header for the table, so far I have attempted two methods: [scrollable]="true" scrollHeight="350px" ...

In React-Redux, attempting to assign a value to an empty string is not permitted

When using the useDispatch hook, I am facing an issue where I cannot set the string to an empty value. Instead, it always sets the value to the last character in the string. App.tsx const dispatch = useDispatch(); dispatch(updateLocation('')); ...

Easy Steps to Simplify Your Code for Variable Management

I currently have 6 tabs, each with their own object. Data is being received from the server and filtered based on the tab name. var a = {} // First Tab Object var b = {} // Second Tab Object var c = {} // Third Tab Object var d = {}// Fou ...

Processing dates with NestJS

I am trying to format a date string in my NestJS API from 'YYYY-mm-dd' to 'dd-mm-YYYY', or even better, into a date object. Unfortunately, the NestJS framework does not seem to recognize when Angular sends a Date as well. Should I be se ...

Template for organizing columns with integrated components

I am looking to create a column in my component that consists of checkboxes. When a checkbox is clicked, I want it to trigger a function within the component. IMPORTANT: It is crucial for me that selecting the row is not allowed, only the function call sh ...

Learn how to dynamically disable a button based on the input state matching an email pattern!

I'm facing an issue with my login form that has 2 input fields and a login button. One of the input fields requires a valid email pattern. If any of the input fields are left empty, the login button becomes disabled. However, when an incorrect email p ...

In the VSCode editor, the color of the text is

Can someone assist me in resolving this issue? I am currently using the one time pad theme, but for some reason, all the code in JavaScript or TypeScript has white text, while other code appears normal. I have attempted to switch to different themes, but ...

What are the ideal scenarios for implementing routing in Angular?

As I embarked on developing my inaugural Angular app, I initially implemented routing with unique URLs for each "main" component. However, upon encountering Angular Material and its appealing tab functionality, I was captivated. What are the advantages an ...

Why is the Last Page display on pagination showing as 3 instead of 2 per items?

When working on Angular 13, I encountered an issue with applying pagination numbers like 1, 2, 3, etc. The problem I faced was that the last page Number should be 2, but it is displaying as 3. Why is this happening? To investigate the issue, I tested my ...

Transferring information from child to parent class in TypeScript

I have a scenario where I have two classes (Model). Can I access properties defined in the child class from the parent class? Parent Class: class Model{ constructor() { //I need the table name here. which is defined in child. } publ ...

angular2-mdl encountered a 404 error and could not be located

I have encountered a strange 404 error stating that the page is not found. Despite installing angular2-mdl using npm install angular2-mdl --save and confirming its presence in the node_modules directory, the error persists. Below is a snippet from my app. ...

The API's post call is throwing an error, yet it functions perfectly when tested on

Currently, I have a functional Angular project that connects to real data using WebAPI2. However, I am now working on an Express.js project for demo purposes which mocks the data, providing random information instead of consuming the actual WebAPI2 data. T ...