错误 TS2322: 类型“number”不能赋值给类型“string”。

7
我正在尝试构建一个应用程序,在这个应用程序中,我想首先按用户获取我的帖子,然后当点击某个帖子时,我想通过id获取该特定的帖子。
最终,我得到了以下错误:
ERROR in src/app/cars/car-detail/car-detail.component.ts(25,11): error TS2322: 类型'Observable<{ _id: string; title: string; content: string; imagePath: string; creator: string; }>'不能赋值给类型'Car[]'。
类型'Observable<{ _id: string; title: string; content: string; imagePath: string; creator: string; }>'中缺少属性'includes'。
src/app/cars/car-detail/car-detail.component.ts(26,11): error 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'];
        }
      );
  }

}

我应该怎么办?

2个回答

5

1)

@Input() id: string 是字符串类型,但是当你执行 this.id = +params['id']; 时,+ 运算符会尝试将 params['id'] 解析为数字类型,因此出现错误。

@Input() id: string 的类型设置为 number

2)

this.post = this.postsService.getPost(this.id);

我认为getPost返回一个可观察对象。你需要订阅它,然后将从调用中返回的结果分配给post属性。

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

当我在我的代码中实现这个时,我会得到以下错误:ERROR in src/app/cars/car-create/car-create.component.ts(45,33): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. src/app/cars/car-detail/car-detail.component.ts(24,61): error TS2322: Type '{ _id: string; title: string; content:string; imagePath: string; creator: string; }' is not assignable to type 'Car[]'. - Tolis
src/app/cars/car-detail/car-detail.component.ts(24,61): 错误 TS2322: 类型 '{ _id: string; title: string; content:string; imagePath: string; creator: string; }' 不能赋值给类型 'Car[]'。 属性 'includes' 在类型 '{ _id: string; title: string; content: string; imagePath: string; creator: string; }' 中不存在。这些错误是由后端代码引起的吗? 我需要在那里做些什么吗? - Tolis

1

当我尝试使用this时,遇到了类似的情况。

错误 TS2322:类型“number”不能赋值给类型“string”

以下是我在实现node 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')的声明类型与产生错误的行的变量类型不兼容。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接