Material Services

Services provides an easier way for passing data. It is a class in your Angular application, let you inject in our components. It centralizes your app. Way to do this, - 

Step 1:    Create a file with name <folder-name>.services.ts
Ex.: 
- Create a class with name <Folder>Service 
- For injecting the dependency add @Injectable({ providedIn : 'root' }) as a decorator of the class.
- Write your code for methods and instances
- export it
import { Post } from './posts.model';
import { Injectable } from '@angular/core';

@Injectable({providedIn: 'root'})
export class PostsService {
  private posts: Post[] = [];

  getPosts(){
    return [...this.posts]; // Spread Operator
  }

  addPost(title: stringcontent: string){
    const newPost: Post = {title, content};
    this.posts.push(newPost);
  }
}

Now we have created a service which creates a new post and adds it to the main posts array. Next we need to inject Dependency to each component for using it. 

Step 2:  Add a Constructor in your component and inject the dependency.

-  Create a constructor inside your component and add the service as a parameter.This will add the instance of the service.
Ex.:
constructor(public postsService: PostsService){}

Now use its methods to add and delete post. 

Comments