Angular16类型不匹配基础问题?
这个 undefined
,是哪里出了问题?感觉很简单,又解决不了。1.todo.service.ts
import { Injectable } from '@angular/core';
import { Todo } from '../interface';
@Injectable({
providedIn: 'root'
})
export class TodoService {
private data: Todo[] = [
{id: 10, description: "For test purpose", category: 1, content: 'test1'},
{id: 12, description: "For test2 ", category: 1, content: 'test2'},
{id: 15, description: "For test3 ", category: 1, content: 'test3'}
]
getTodo(id: number): Todo {
return this.data.find(item => item.id ===id)
}
- interface
export interface Todo {
id: number;
description: string;
category: number;
content: string;
}
export enum Category {
html,
css,
js
}
- details
export class DetailComponent implements OnInit{
todo!: Todo;
constructor(private route: ActivatedRoute, private todoServe: TodoService) {}
ngOnInit(): void {
const id = Number(this.route.snapshot.paramMap.get('id'))
this.todo = this.todoServe.getTodo(id)
}
}
回复
1个回答
test
2024-06-26
如果你能确保 id 一定在数组中找得到的话 直接采用(!)非空断言即可。
getTodo(id: number): Todo {
return this.data.find(item => item.id ===id)!
}
回复
适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容