Skip to main content

Command Palette

Search for a command to run...

Angular: @Services

Published
1 min read
Angular: @Services
S

I love learning about technology and sharing that with others

Introduction

so we can use service to make the HTTP requests for us so that our template will be clean and we can make the rest calls in the service.

Pattern1

Deal with the observable in the service.

Pattern 2 :

deal with he observable means subscribe to the service in the component, where we are using the service.

Example Service

```import { HttpClient } from "@angular/common/http"; import { Injectable } from "@angular/core"; import { Post } from "./post.model"; import { map } from "rxjs/operators"

@Injectable({providedIn:'root'}) export class PostsService {

constructor(private http:HttpClient) {

}


createAndAddPosts(title:string,content:string) {
    const postData:Post= {title:title,content:content};

    this.http.post('https://ngfirstproject-default-rtdb.asia-southeast1.firebasedatabase.app/posts.json',
postData
).subscribe( responseData=> {
  console.log(responseData)
} )
}

fetchPosts() {

  return  this.http.get< { [key:string]:Post  } >('https://ngfirstproject-default-rtdb.asia-southeast1.firebasedatabase.app/posts.json')
    .pipe( 
      map(responseData => {

      const postArray=[];

      for (const key in responseData) {
        if(responseData.hasOwnProperty(key)) {
        postArray.push( { ...responseData[key] , id:key} )
        }
      }
      return postArray;
    })

    );

  }

}



#### Component calling the service.

here we are subscribed in the component.

onFetchPosts() {

this.postService.fetchPosts().subscribe( posts=>{
  this.loadedPosts=posts;

} )

} ```

4 views

More from this blog

H

hashcodehub

271 posts

Consistent, Passionate and Organized :)

Angular: @Services