Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post data to API with or without subscribe

In Angular 7 I am getting and posting data from an API.

GET

  • To get data I am using an Observable (posts$) and pipe / map;
  • I am using async in the Component HTML and not using Subscribe;
  • This is the approach I have seen recently including in Angular docs.

POST

  • The Service Post method also returns data:
    Possible validation errors or the ID of the created Post.
    I need to get any of them when they are returned by the API.

However, when calling the service to POST the following does nothing:

this.postService.addPost(model).pipe();

Unless I use subscribe as follows:

this.postService.addPost(model).pipe().subscribe();

Question How would I post to the API without using subscribe? And does it make sense?

Component

export class PostComponent implements OnInit {

  posts$: Observable<GetPostsModel[]>;

  constructor(private postService: PostService) { }

  ngOnInit() {
    this.posts$ = this.getPosts();
  }

  addPost(model: AddPostModel) {

    this.postService.addPost(model).pipe().subscribe();

  }

  getPosts(): Observable<GetPostsModel[]> {

    return this.postService.getPosts().pipe(

      map((response: GetPostsResponse) => 

        return {
          // Map Response to GetPostsModel here 
        };

      }));

  }

}

Service

export class PostService {

  constructor(private httpClient: HttpClient) { }

  public addPost(model: AddPostModel): Observable<AddPostResponse>> {

    const headers = new HttpHeaders({ 'Content-Type': 'application/json' });

    return this.httpClient.post<AddPostResponse>>('posts', model, { headers: headers });

  }

  public getPosts(): Observable<GetPostsResponse>> {
    return this.httpClient.get<GetPostsResponse>>('posts');
  }

}
like image 681
Miguel Moura Avatar asked Sep 07 '25 07:09

Miguel Moura


1 Answers

How would I post to the API without using subscribe?

You can't, you must always subscribe. If you do not care about the result you do not have to supply a callback. This is perfectly valid:

this.postService.addPost(model).subscribe();

side note: you do not need an empty pipe in this case

See also Angular 2 http.post() is not sending the request and HttpClient - Always subscribe! documentation.

Always subscribe!

An HttpClient method does not begin its HTTP request until you call subscribe() on the observable returned by that method. This is true for all HttpClient methods.

like image 123
Igor Avatar answered Sep 09 '25 23:09

Igor