Skip to content

Instantly share code, notes, and snippets.

@MatthewKosloski
Created June 25, 2020 10:00
Show Gist options
  • Save MatthewKosloski/a1fdef16914aa3b2e69519cfc8b40c63 to your computer and use it in GitHub Desktop.
Save MatthewKosloski/a1fdef16914aa3b2e69519cfc8b40c63 to your computer and use it in GitHub Desktop.
Unwrapped todos
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { OnInit } from '@angular/core';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
interface Todo {
userId: number
id: number
title: string
completed: boolean
}
interface UnwrappedTodo {
title: string
id: number
}
type UnwrappedTodos = UnwrappedTodo[];
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'angular-tests';
unwrappedTodos: UnwrappedTodos;
constructor(private http: HttpClient) {}
getTodos(): Observable<Todo[]> {
return this.http.get<Todo[]>('https://jsonplaceholder.typicode.com/todos/');
}
unwrapTodo({title, id}: Todo): UnwrappedTodo {
return {title, id};
}
unwrapTodos() {
return (source: Observable<Todo[]>) => {
return source.pipe(
map((todos: Todo[]) => todos.map((todo: Todo) => this.unwrapTodo(todo)))
)
}
}
setUnwrappedTodos(unwrappedTodos: UnwrappedTodos) {
this.unwrappedTodos = unwrappedTodos;
}
ngOnInit() {
this.getTodos()
.pipe(this.unwrapTodos())
.subscribe((unwrappedTodos: UnwrappedTodos) => {
this.setUnwrappedTodos(unwrappedTodos);
console.log(this.unwrappedTodos);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment