我想從一個或多個 Observable 陣列回傳一個 Observable 物件。getTodoById() 我嘗試使用管道和映射運算子回傳。錯誤訊息:
輸入'Observable<Todo | undefined>' 不能輸入'Observable'。輸入'待辦事項 | undefined 不可分配給型別“Todo”。ts(2322)
我嘗試分配“?” 標志,但它不是很有用。也許我做錯了。這是我目前的代碼。我試過 Observable<Todo | undefined> 作為 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
}
uj5u.com熱心網友回復:
您是否嘗試過添加過濾器運算子
return this.todos$.pipe(
map(todos=> todos.find(todo => todo._id === id)),
filter(todo => !!todo)
)
uj5u.com熱心網友回復:
您需要將 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>
}
但我更喜歡第一個解決方案
uj5u.com熱心網友回復:
感謝您的回答并嘗試提供幫助。我決定采用一種更簡單的方法,即:
public getById(id: string): Todo | undefined{
const todos = this._todos$.getValue();
return todos.find(todo => todo._id === id);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/352511.html
