[英]Angular 11.2.6 or Typescript TS2345 error
I am working on an Angular tutorial that provides some code but I am receiving an error that I have been unable to resolve.我正在编写 Angular 教程,该教程提供了一些代码,但我收到了一个我无法解决的错误。 Everywhere in my code where I have dish or getDish it is a string.
在我的代码中我有菜或getDish的任何地方都是一个字符串。 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.我已经尝试回顾教程并将所有说明与我推送到 Github 的每个版本相匹配。 I am very new to Angular so maybe the tutorial is using a different version?
我对 Angular 很陌生,所以也许教程使用的是不同的版本?
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菜细节.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菜服务.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 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.如果您需要其他文件,我可以提供。
Remove the +
from删除
+
从
const id = +this.route.snapshot.params['id'];
to get:要得到:
const id = this.route.snapshot.params['id'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.