类型 'Observable<Post | undefined>' 不可分配给类型 'Observable<Post>'



我刚开始使用Angular,我正试图用Firebase + Angular建立一个博客。然而,我得到了一个错误,我无法理解如何修复。我有一个blog.service.ts文件,我把不同的服务。问题是我得到上述错误的getPostById()方法。这里是GitHub repo的链接:https://github.com/achakarov/blogsite-angular

代码如下:

import { Injectable } from '@angular/core';
import { AngularFirestore } from '@angular/fire/firestore';
import { Post } from '../models/post';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class BlogService {
constructor(private db: AngularFirestore) {}
createPost(post: Post) {
const postData = JSON.parse(JSON.stringify(post));
return this.db.collection('blogs').add(postData);
}
getPostbyId(id: string): Observable<Post> {
const blogDetails = this.db.doc<Post>('blogs/' + id).valueChanges();
return blogDetails;
}
}

这是我使用服务的blog-card组件:

import { Component, OnInit } from '@angular/core';
import { OnDestroy } from '@angular/core';
import { BlogService } from 'src/app/services/blog.service';
import { Post } from 'src/app/models/post';
import { Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-blog-card',
templateUrl: './blog-card.component.html',
styleUrls: ['./blog-card.component.scss'],
})
export class BlogCardComponent implements OnInit, OnDestroy {
blogPost: Post[] = [];
private unsubscribe$ = new Subject<void>();
constructor(private blogService: BlogService) {}
ngOnInit(): void {
this.getBlogPosts();
}
getBlogPosts() {
this.blogService
.getAllPosts()
.pipe(takeUntil(this.unsubscribe$))
.subscribe((result) => {
this.blogPost = result;
});
}
delete(postId: string) {
// Method definition to be added later
}
ngOnDestroy() {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}
}
最后,post.ts文件如下:
export class Post {
postId: string | undefined;
title: string | undefined;
content: string;
author: string | undefined;
createdDate: any;
constructor() {
this.content = '';
}
}

有人可以帮我解决这个问题,因为我有我的头撞在墙上?

Type 'Observable

这样的错误是由于类型检查,错误很好地描述了问题。问题是,该课程中的类型检查可能不像您的项目中那样严格。Angular 12甚至在项目创建时都不会问你是否要使用"strict模式",现在只是默认为strict。

你基本上不能设置一个可以将undefined返回给期望被定义的变量的对象。

根据你的情况和期望的行为:

  • 使用Observable<Post | undefined>作为接收值的类型
  • 检查是否传入的可观察对象不是undefined类型:
    if (yourObs != Observable<undefined>){
    your logic...
    }
    
  • 在其他情况下,您可以在变量后面使用确定赋值(!)来告诉编译器确信变量将被赋值(我认为这对您的情况没有帮助)
  • 在项目中关闭严格模式(我不建议这样做)。最好学会使用严格的类型)

更新getPostById方法以返回Observable<Post|undefined>而不是Observable<Post>,因为在该方法中可能会返回undefined

相关内容

最新更新