【发布时间】: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;
}
【问题讨论】:
-
我推荐阅读the docs,它向您展示了如何设置泛型类型。还有很多相关的问题,例如stackoverflow.com/q/50492977/3001761。你研究过这个吗?
标签: angular typescript rxjs observable