error TS2322: Type 'number' is not assignable to type 'string'

Refresh

November 2018

Views

516 time

2

I am trying to build an app, where I want to get my posts, at first, by user and then when a post is clicked, I want to get this particular post by id.

And finally I get the following errors:

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[]'.

Property 'includes' is missing in type 'Observable<{ _id: string; title: string; content: string; imagePath: string; creator: string; }>'.

src/app/cars/car-detail/car-detail.component.ts(26,11): error TS2322: Type 'number' is not assignable to type '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'];
        }
      );
  }

}

What should I do?

1 answers

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);