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

时间:2018-08-30 14:10:00

标签: angular typescript get-request

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

最后我得到以下错误:

  src / app / cars / car-detail / car-detail.component.ts(25,11)中的

ERROR:错误   TS2322:类型为“ Observable <{_id:字符串; title:字符串内容:   串; imagePath:字符串;创建者:字符串; }>'不可分配给   输入“ Car []”。

类型'Observable <{_id:string;中缺少属性'includes' title:字符串内容:字符串; imagePath:字符串;创建者:字符串; }>'。

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

}

我该怎么办?

2 个答案:

答案 0 :(得分:2)

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返回一个可观察的。您需要订阅它,然后将调用返回的结果分配给post属性。

this.postsService.getPost(this.id).subscribe(res => this.post = res);

答案 1 :(得分:1)

尝试this时遇到了类似的情况。

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

以下是我在实现节点rest api时遇到的错误。

error TS2322: Type 'string' is not assignable to type 'number | FindOperator<number>'.

27     const product = await repository.find({ id: req.params.id });

我只需要简单地将变量类型从id:number更改为id: string

此函数中使用的关联变量在另一个文件中声明。该特定变量的声明类型(在我的示例中为“ id”)与产生错误的行的变量类型不兼容。

因此转到声明的位置,然后根据类型将变量类型设置为数字/字符串,然后它将与其余功能兼容。

相关问题