输入'可观察的<发布| undefined>' 不可分配给类型 'Observable<Post>'

时间:2021-07-31 13:20:16

标签: angular typescript rxjs

我刚刚开始使用 Angular,我正在尝试使用 Firebase + Angular 构建一个博客。但是,我收到一个错误,我无法理解如何修复。我有一个 blog.service.ts 文件,用于放置不同的服务。问题在于我收到上述错误的 getPostById() 方法。以下是 GitHub 存储库的链接: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 = '';
  }
}

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

2 个答案:

答案 0 :(得分:1)

<块引用>

输入'Observable' 不可分配给类型 '可观察'

像这样的错误是因为类型检查,错误很好地描述了问题。问题是该课程中的类型检查可能不像您的项目中那样严格。如果您想使用“严格模式”,Angular 12 甚至不会询问项目创建,现在只是默认为严格。

您基本上无法设置可以将 undefined 返回到预期定义的变量的对象。

取决于您的情况和所需的行为:

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

答案 1 :(得分:0)

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