Created
June 28, 2022 11:10
-
-
Save wpflames/4a9e5517f7c590bd46cb73d8d88317ec to your computer and use it in GitHub Desktop.
Create a new post object and display it in the top of our list in the browser
This file contains hidden or 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 { HttpClient } from '@angular/common/http'; | |
| import { Component } from '@angular/core'; | |
| @Component({ | |
| selector: 'posts', | |
| templateUrl: './posts.component.html', | |
| styleUrls: ['./posts.component.scss'] | |
| }) | |
| export class PostsComponent { | |
| posts: any; | |
| private url = 'https://jsonplaceholder.typicode.com/posts'; | |
| constructor(private http: HttpClient) { | |
| http.get(this.url).subscribe(res => { | |
| console.log(res); | |
| this.posts = res; | |
| }); | |
| } | |
| createPost(input: HTMLInputElement){ | |
| let post = { title: input.value }; | |
| input.value = ''; | |
| this.http.post(this.url, JSON.stringify(post)) | |
| .subscribe(res => { | |
| post['id'] = res['id']; | |
| this.posts.splice(0, 0, post); | |
| console.log(res); | |
| }) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment