In my Angular 7 project, I initially had the following code for the Envelope class:
export class Envelope<T> {
result: T[];
constructor(result: T[]) {
this.result = result;
}
}
Then, I mapped
Observable<Envelope<Todo>>
returned by todoService to 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
};
})));
However, the structure of Envelope has now changed to result: T
instead of result: T[]
:
export class Envelope<T> {
result: T;
constructor(result: T) {
this.result = result;
}
}
Now, I need to map
Observable<Envelope<Todo[]>>
to the same 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
};
})));
I have tried various options but am encountering the following error:
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.
If anyone could provide guidance on how to successfully do the mapping, it would be greatly appreciated.
Update
The API response looks like this:
{
"result": [
{ "id": 1, "title": "T1", content: "C1" },
{ "id": 2, "title": "T2", content: "C2" }
]
}
And the TodoService returns it as an
Observable<Envelope<Todo[]>>
where Todo
is defined as:
interface Todo {
id: number;
title: string;
content: string;
}
In the component, I need to map
Observable<Envelope<Todo[]>>
to Observable<TodoModel[]>
where TodoModel
is defined as:
interface TodoModel {
title: string;
content: string;
}
While my application has more complex scenarios, this is the basic structure I am working with.