角度/打字稿错误:类型'Observable <未知>'不能分配给类型'Observable <Blogpost>'

时间:2020-04-16 15:11:59

标签: angular typescript rxjs observable

我正在尝试在我的角度应用程序中调用服务,但是在此行this.currentBlog = this.route.paramMap.pipe(上的ngOnInIt函数上收到以下错误

类型“可观察”不能分配给类型“可观察”。类型“ {}”缺少类型“博客文章”中的以下属性:id,title,short_desc,description和另外3个。

component.ts文件:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute, ParamMap} from '@angular/router';
import { switchMap } from 'rxjs/operators';
import { BlogpostService } from '../blogpost.service';
import { Blogpost } from '../../models/blogpost';

@Component({
  selector: 'app-blog-detail',
  templateUrl: './blog-detail.component.html',
  styleUrls: ['./blog-detail.component.css']})
export class BlogDetailComponent implements OnInit, OnDestroy {
  public currentBlog: Observable<Blogpost>;

  constructor(private route: ActivatedRoute,private router: Router,private blogpostService: BlogpostService) {}
  ngOnInit() {
       this.currentBlog = this.route.paramMap.pipe(
                  switchMap((params: ParamMap) =>
                    this.blogpostService.getSingleBlogInformation(+params.get('id'))));
}
  ngOnDestroy(){
    ('blog-detail component destroyed')
  }}

Blogpost.ts:

export class Blogpost {
    id: number;
    title: string;
    short_desc: string;
    description: string;
    author: string;
    image: string;
    created_at: Date;}

Service.ts:

public getSingleBlogInformation(currentBlogId): any {
    let myResponse = this._http.get(this.baseUrl + 'getById.php?id=' + currentBlogId).pipe(
      catchError(this.handleError)
    );
    return myResponse;
  }

2 个答案:

答案 0 :(得分:0)

您需要输入服务方法的返回值:

public getSingleBlogInformation(currentBlogId): Observable<Blogpost> {
    return this._http.get<Blogpost>(this.baseUrl + 'getById.php?id=' + currentBlogId).pipe(
      catchError(this.handleError)
    );
  }

答案 1 :(得分:0)

首先,您无需在let中创建Service.ts即可返回HTTP请求的结果。

Service.ts:

public getSingleBlogInformation(currentBlogId): Observable<Blogpost> {
    return this._http.get<Blogpost>(this.baseUrl + 'getById.php?id=' + currentBlogId).pipe(
      catchError(this.handleError)
    );
  }

另外,请记住,此调用返回一个Observable,在这种情况下返回:Observable<Blogpost>

在那之后,它现在应该可以工作了。