我正在尝试构建一个应用程序,首先我想通过用户获取我的帖子,然后当点击帖子时,我想通过 ID 获取这个特定的帖子。
最后我得到以下错误:
ERROR in src/app/cars/car-detail/car-detail.component.ts(25,11): error TS2322: Type 'Observable<{ _id: string; title: string; content: string; imagePath: string; creator: string; }>' is not assignable to type 'Car[]'.
'Observable<{ _id: string; 类型中缺少属性'includes';标题:字符串;内容:字符串;图片路径:字符串;创建者:字符串; }>'.
src/app/cars/car-detail/car-detail.component.ts(26,11):错误 TS2322:类型“数字”不可分配给类型“字符串”。
import { Input, Component, OnInit } from '@angular/core';
import { Car } from '../car.model';
import { CarsService } from '../cars.service';
import { ActivatedRoute, Params } from '@angular/router';
@Component({
selector: 'app-post-detail',
templateUrl: './post-detail.component.html',
styleUrls: ['./post-detail.component.css']
})
export class PostDetailComponent implements OnInit {
@Input() post: Post[] = [];
@Input() id: string;
constructor(
private postsService: PostsService,
private route: ActivatedRoute
) { }
ngOnInit() {
this.route.params
.subscribe(
(params: Params) => {
this.post = this.postsService.getPost(this.id);
this.id = +params['id'];
}
);
}
}
我该怎么办?
最佳答案
1)
@Input() id: string
是 string
类型,但是当您执行 this.id = +params['id'];
- +
运算符尝试将 params['id']
解析为 number
,所以为什么会出现错误。
将@Input() id: string
的类型设置为number
。
2)
this.post = this.postsService.getPost(this.id);
我认为 getPost
返回一个 observable。您需要订阅它,然后将调用返回的结果分配给 post
属性。
this.postsService.getPost(this.id).subscribe(res => this.post = res);
关于angular - 错误 TS2322 : Type 'number' is not assignable to type 'string' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52099134/