[Fixed] Angular 11.2.6 or Typescript TS2345 error

Issue

I am working on an Angular tutorial that provides some code but I am receiving an error that I have been unable to resolve. Everywhere in my code where I have dish or getDish it is a string. The string does contain a number but it is always a string.

I have tried going back through the tutorial and matched all of the instructions with each version I pushed to Github. I am very new to Angular so maybe the tutorial is using a different version?

The error is

Error: src/app/dishdetail/dishdetail.component.ts:23:42 - error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.

23     this.dish = this.dishservice.getDish(id);  
                                            ~~

dishdetail.component.ts

import { Component, OnInit } from '@angular/core';
import { Dish } from '../shared/dish';
import { DishService } from '../services/dish.service';

import { Params, ActivatedRoute } from '@angular/router';
import { Location } from '@angular/common';

@Component({
  selector: 'app-dishdetail',
  templateUrl: './dishdetail.component.html',
  styleUrls: ['./dishdetail.component.scss']
})
export class DishdetailComponent implements OnInit {

  dish: Dish;

  constructor(private dishservice: DishService,
    private route: ActivatedRoute,
    private location: Location) { }

  ngOnInit() {
    const id = +this.route.snapshot.params['id'];
    this.dish = this.dishservice.getDish(id);
  }

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

}

dish.service.ts

import { Injectable } from '@angular/core';
import { Dish } from '../shared/dish';
import { DISHES } from '../shared/dishes';

@Injectable({
  providedIn: 'root'
})
export class DishService {

  constructor() { }

  getDishes(): Dish[] {
    return DISHES;
  }

  getDish(id: string): Dish {
    return DISHES.filter((dish) => (dish.id === id))[0];
  }

  getFeaturedDish(): Dish {
    return DISHES.filter((dish) => dish.featured)[0];
  }
}

menu.component.ts

import { Component, OnInit } from '@angular/core';
import { Dish } from '../shared/dish';
import { DISHES } from '../shared/dishes';
import { DishService } from '../services/dish.service';


@Component({
  selector: 'app-menu',
  templateUrl: './menu.component.html',
  styleUrls: ['./menu.component.scss']
})
export class MenuComponent implements OnInit {

  dishes: Dish[] = DISHES;

  selectedDish: Dish;

  constructor(private dishService: DishService) { }

  ngOnInit() {
    this.dishes = this.dishService.getDishes();
  }

  onSelect(dish: Dish) {
    this.selectedDish = dish;
  }

}

If you need other files I can provide them.

Solution

Remove the + from

const id = +this.route.snapshot.params['id'];

to get:

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

Leave a Reply

(*) Required, Your email will not be published