【问题标题】:Angular returning observable object from Objservable Array of objects:Angular 从 Objservable 对象数组返回 observable 对象:
【发布时间】:2021-11-07 12:06:39
【问题描述】:

我想从一个或多个 Observable 数组中返回一个 Observable 对象。 getTodoById() 我尝试使用管道和地图运算符返回。 错误消息:

输入'Observable' 不能输入 'Observable'。输入“待办事项 | undefined 不可分配给类型“Todo”。 ts(2322)

我尝试分配“?”签名,但它不是很有用。也许我做错了。 这是我当前的代码。 我试过 Observable 作为 getById() 的返回类型,它显示了相同的错误。

待办事项:

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable, of, Subscription, pipe } from 'rxjs';
import { map } from 'rxjs/operators';
import { FilterBy } from '../models/filterBy.model';
import { SortBy } from '../models/sortBy.model';
import { Todo } from '../models/todo.model';

// this is BehaviorSubject - Can get .next
  private _todos$ = new BehaviorSubject<Todo[]>([])

  // this is an Observable - we CANNOT do .next.
  // It acts like a getter - You can list to it's changes
  // this makes a good separation!
  public todos$ = this._todos$.asObservable();

      public getById(id: string): Observable<Todo> {
    return this.todos$.pipe(map(todos=> todos.find(todo => todo._id === id)))
  }

待办事项模型:

export interface Todo {
  _id: string,
  title:string,
  date:Date,
  isDone:boolean,
  importance:number
}

【问题讨论】:

  • 可观察的
  • 没有帮助。添加:Observable 作为 getVyId @MikeOne 的返回类型
  • Array.prototype.find() 返回找到的项目或undefined。更改函数的返回类型应该可以解决。更改后您是否收到其他错误?
  • 你能试试.filter()而不是map and find吗?
  • @BizzyBob - 更改返回类型后我得到了确切的错误(添加未定义)

标签: angular rxjs angular2-observables rxjs-observables


【解决方案1】:

您是否尝试过添加过滤器操作符

return this.todos$.pipe(
  map(todos=> todos.find(todo => todo._id === id)),
  filter(todo => !!todo)
)

【讨论】:

  • 为什么要使用过滤器??
【解决方案2】:

您需要将 undefined 作为返回类型添加到 getById,因为您使用的是 find() 并且 typescript 足够聪明,知道您的数组不会总是返回值。

  public getById(id: string): Observable<Todo | undefined> {
    return this.todos$.pipe(map(todos=> todos.find(todo => todo._id === id)))
  }

或者,如果您不想将 undefined 作为返回值返回,您可以按如下方式使用强制转换:

  public getById(id: string): Observable<Todo> {
    return this.todos$.pipe(map(todos=> todos.find(todo => todo._id === id))) as Observable<Todo>
  }

但我更喜欢第一种解决方案

【讨论】:

    【解决方案3】:

    感谢您的回答并尽力提供帮助。我决定采用一种更简单的方法:

      public getById(id: string): Todo | undefined{
        const todos = this._todos$.getValue();
        return todos.find(todo => todo._id === id);
      }
    

    【讨论】:

    • "来自 RxJS 5 的作者的重要说明:使用 getValue() 是一个巨大的危险信号,你做错了。它作为一个逃生舱口存在。通常你对 RxJS 所做的一切都应该是声明性的. getValue() 是必要的。如果您使用 getValue(),则有 99.9% 的机会您做错或奇怪的事情。– Ben Lesh 2017 年 7 月 21 日 0:01 链接:stackoverflow.com/questions/37089977/…(请参阅答案)
    猜你喜欢
    • 2018-11-12
    • 2019-06-25
    • 1970-01-01
    • 2018-07-08
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    相关资源
    最近更新 更多