使用Angular 7我有这个:
export class Envelope<T> {
result: T[];
constructor(result: T[]) {
this.result = result;
}
}
我将Observable<Envelope<Todo>>
(由todoService返回)映射到Observable<TodoModel[]>
:
let models: Observable<TodoModel[]> = this.todoService.get()
.pipe(
map((envelope: Envelope<Todo>) =>
envelope.result.map((todo: Todo) => {
return {
content: todo.content
// Other properties
};
})));
这是可行的,但是现在信封更改为(result: T
而不是result: T[]
):
export class Envelope<T> {
result: T;
constructor(result: T) {
this.result = result;
}
}
我需要将Observable<Envelope<Todo[]>>
映射到相同的Observable<TodoModel[]>
:
let models: Observable<TodoModel[]> = this.todoService.get()
.pipe(
map((envelope: Envelope<Todo[]>) =>
envelope.result.map((todo: Todo) => {
return {
content: todo.content
// Other properties
};
})));
我尝试了一些选项,但出现以下错误:
Argument of type 'OperatorFunction<Envelope<Todo[]>, { content: string; }[]>'
is not assignable to parameter of type 'OperatorFunction<Envelope<Todo>, { content: string; }[]>'.
Type 'Envelope<Todo[]>' is not assignable to type 'Envelope<Todo>'.
Type 'Todo[]' is missing the following properties from type 'Response': content.
能不能让我知道如何进行映射?
更新
例如,API返回以下内容:
{
"result": [
{ "id": 1, "title": "T1", content: "C1" },
{ "id": 2, "title": "T2", content: "C2" }
]
}
然后TodoService将其作为Observable<Envelope<Todo[]>>
返回,其中Todo
是:
interface Todo {
id: number;
title: string;
content: string;
}
在组件中,我需要将Observable<Envelope<Todo[]>>
映射到Observable<TodoModel[]>
所在的TodoModel
:
interface TodoModel {
title: string;
content: string;
}
我的应用程序中有更复杂的场景,但是基础是这个。
答案 0 :(得分:0)
您需要观察信封吗?也许这样的事情会更直接。如果信封上有待办事项清单
result: Observable<TodoModel>;
this.todoService.get()
.subscribe((envelope: any) => {
this.result = envelope.todo.content;
});