【问题标题】:Type 'Observable<User | null | undefined>键入'可观察<用户 |空 |未定义>
【发布时间】:2021-08-07 00:00:45
【问题描述】:

我有一个无法解决的问题,我已经阅读了几个类似的问题,但我不明白它失败了,每种情况似乎都与我的不同。

我正在尝试获取 id 以从 firebase 获取我的博客数据。

这是我的问题:

错误:src / app / components / blogs / blog.service.ts:26:5 - 错误TS2322:类型'Observable '不可分配给类型' Observable '。 键入“博客界面 | undefined '不可分配给类型' BlogsInterface '。 类型“未定义”不能分配给类型“BlogsInterface”。 26 返回博客ID;

这是我的代码:

import { Injectable } from '@angular/core';
import { AngularFirestoreModule } from '@angular/fire/firestore';
import { AngularFirestore } from '@angular/fire/firestore';
import { BlogsInterface } from '../../models/blogs.interface';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class BlogService {
  constructor(private angularFS: AngularFirestore) { }
  
  public getBlogs():Observable<BlogsInterface[]>{
    
    return this.angularFS
        .collection('blogs')
        .snapshotChanges()
        .pipe(
            map(actions => actions.map(a => {
                const data = a.payload.doc.data() as BlogsInterface;
                const id = a.payload.doc.id;
                return {id, ... data};
            }))
        )
  }

  public getBlogId(id: BlogsInterface):Observable<BlogsInterface>{
    const BlogId = this.angularFS.doc<BlogsInterface>(`blogs/${id}`).valueChanges();
    return BlogId;
  }
}

感谢您的帮助,如果我没有很好地解释自己或犯了错误,请原谅我,这是我的第一次。

【问题讨论】:

  • 也许angularFS.doc 可能会返回undefined,所以你应该将它添加到你的返回类型getBlogId(id: BlogsInterface):Observable&lt;BlogsInterface | undefined&gt;

标签: angular typescript firebase google-cloud-firestore


【解决方案1】:

如果您使用的是 Visual Studio Code,您可以右键单击 .valueChanges > 转到定义并查看其输入:

export declare class AngularFirestoreDocument<T = DocumentData> {
    ...

    /**
     * Listen to unwrapped snapshot updates from the document.
     *
     * If the `idField` option is provided, document IDs are included and mapped to the
     * provided `idField` property name.
     */
    valueChanges(options?: {}): Observable<T | undefined>;

    ...
}

你需要输入

public getBlogId(id: BlogsInterface):Observable<BlogsInterface | undefined>

或将undefined 映射到匹配BlogsInterface 类型的对象(如果这对您的应用程序有意义)

.valueChanges().pipe(
    map(x => {
        if (x === 'undefined') {
            // give a value
        }
        return x
    }))

【讨论】:

  • 您好,非常感谢您这么快回复。 public getBlogId (id: BlogsInterface): Observable &lt;BlogsInterface | undefined&gt; 有了这个解决方案,错误消失了,但我得到了未定义的值,所以它对我不起作用,因为我需要 ID 来打开每个帖子的内容。我不明白的其他解决方案。
  • @DanielGarcía 您必须处理 undefined 案例,例如在使用前检查并在警卫中重新路由说或显示 UI 消息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
  • 2013-12-21
  • 2018-03-27
相关资源
最近更新 更多