错误 TS2322:“数字”类型不可分配给“字符串”类型

Tol*_*lis 6 get-request typescript angular

我正在尝试构建一个应用程序,我想首先按用户获取我的帖子,然后在单击帖子时,我想按 id 获取此特定帖子。

最后我收到以下错误:

src/app/cars/car-detail/car-detail.component.ts(25,11) 中的错误:错误 TS2322:类型 'Observable<{ _id: string; 标题:字符串;内容:字符串;图像路径:字符串;创建者:字符串;}>' 不能分配给类型 'Car[]'。

'Observable<{ _id: string; 类型中缺少属性'includes' 标题:字符串;内容:字符串;图像路径:字符串;创建者:字符串;}>'。

src/app/cars/car-detail/car-detail.component.ts(26,11): 错误 TS2322: 类型 'number' 不能分配给类型 'string'。

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'];
        }
      );
  }

}
Run Code Online (Sandbox Code Playgroud)

我该怎么办?

Sur*_*yan 5

1)

@Input() id: string是类型string,但是当你这样做时this.id = +params['id'];-+运算符尝试解析params['id']number,所以为什么你会得到错误。

将 的类型设置@Input() id: stringnumber

2)

this.post = this.postsService.getPost(this.id);
Run Code Online (Sandbox Code Playgroud)

我认为getPost返回一个observable。您需要订阅它,然后将调用返回的结果分配给该post属性。

this.postsService.getPost(this.id).subscribe(res => this.post = res);
Run Code Online (Sandbox Code Playgroud)