Skip to content

Instantly share code, notes, and snippets.

@ABooooo
Last active February 21, 2022 20:52
Show Gist options
  • Save ABooooo/6c2c28a9fad18c96cac6cd152fd142ae to your computer and use it in GitHub Desktop.
Save ABooooo/6c2c28a9fad18c96cac6cd152fd142ae to your computer and use it in GitHub Desktop.
// 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