Last active
February 21, 2022 20:52
-
-
Save ABooooo/6c2c28a9fad18c96cac6cd152fd142ae to your computer and use it in GitHub Desktop.
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
// model | |
// ts | |
export interface Post { | |
// some data for example | |
title: string; | |
content: string; | |
} | |
// service | |
// ts | |
import { Post } from 'path to post model'; | |
@Injectable({provadedIn: 'root'}) // read the comment at the bottom | |
export class PostService { | |
private posts: Post[] = []; | |
getPosts() { | |
return this.posts; | |
} | |
addPosts(title: string, content: string) { | |
const post: Post = { | |
title: title, | |
content: content | |
} | |
this.posts.push(post); | |
} | |
} | |
// component 1 | |
//ts | |
import { PostService } from 'path to post service'; | |
export class className implements OnInit { | |
constructor(public postsService: PostsService) {} | |
onAddPost(form: NgForm) { // for html and detailed form explanation look snippet "Data from From with validation" | |
if (form.invalid) { | |
return; | |
} | |
this.postsService.addPost(form.value.title, form.value.content); | |
} | |
} | |
// component 2 | |
// ts | |
import { Post } from 'path to post model'; | |
import { PostService } from 'path to post service'; | |
export class className implements OnInit { | |
posts: Post[] = []; | |
// this is a short version of | |
constructor(public postsService: PostsService) {} | |
// of this | |
/* | |
postService: PostService; | |
constructor(postsService: PostsService) { | |
this.postsService = postsService; | |
} | |
*/ | |
ngOnInit() { | |
this.posts = this.postsService.getPosts(); | |
} | |
} | |
// ********** // | |
// // @Injectable({provadedIn: 'root'}) this is the same as insert service in app.module.ts under providers |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment