angular - 错误 TS2322 : Type 'number' is not assignable to type 'string'

标签 angular typescript get-request

我正在尝试构建一个应用程序,首先我想通过用户获取我的帖子,然后当点击帖子时,我想通过 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: stringstring 类型,但是当您执行 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/

相关文章:

javascript - 我如何查看设置的计时器倒计时 Angular 7

tomcat - 替换 nginx 或 Tomcat 中的 GET 值

c - GET请求获取页面内容

angular - 有没有办法在 Angular 7 中命名一条路线?

angular - 类型错误 : Cannot read property 'length' of undefined (Angular 8)(header)

javascript - 如何使用ng2-charts和chart.js在环外的固定位置绘制极坐标图的外部标签?

angular - ngmodule.type - 无法读取 null 的属性类型 - main.js

条件类型的 typescript 枚举类型检查?

javascript - 类型缺少调用签名

android - 在使用 Retrofit 调用获取 Web 服务请求时。 "android.os.TransactionTooLargeException: data parcel size 1575704 bytes"