【问题标题】:Angular/typescript error: Type 'Observable<unknown>' is not assignable to type 'Observable<Blogpost>'Angular/typescript 错误:类型 'Observable<unknown>' 不可分配给类型 'Observable<Blogpost>'
【发布时间】:2020-07-29 21:33:51
【问题描述】:

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

类型“Observable”不可分配给类型“Observable”。类型“{}”缺少类型“Blogpost”中的以下属性: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;
  }

【问题讨论】:

标签: angular typescript rxjs observable


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    首先,您无需在Service.ts 中创建let 即可返回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&lt;Blogpost&gt;。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-28
      • 2021-10-28
      • 1970-01-01
      • 2020-01-10
      • 2020-04-17
      • 2020-01-10
      • 1970-01-01
      • 2019-02-07
      相关资源
      最近更新 更多