Created
June 25, 2020 10:00
-
-
Save MatthewKosloski/a1fdef16914aa3b2e69519cfc8b40c63 to your computer and use it in GitHub Desktop.
Unwrapped todos
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
https://stackoverflow.com/questions/42238819/angular-2-how-to-call-a-function-after-get-a-response-from-subscribe-http-post