Ninja Space Content Tech Blog

Week Eight of Learning Angular

Posted by Ninja Space Content on Sunday, July 11, 2021 Under: angular
This is my Week 8 of learning Angular. Sorry, I went off track for awhile. It's been 2 months since I wrote up my notes for Week 7. (See all of my learning notes for Angular.) I picked up a contract job towards the end of May and that had been my focus. This week I am focusing on error handling in Angular.

  1. Use onInit method to call http services and constructor should not call http services. Oninit is a lifestyle hook. When we use the ng onInit method, we tell the compiler about it.
  2. We want to implement Separate of Concerns. For example, don't include delete responsibility in the same class or service of a new post because it is hard to maintain and test.
  3. To create a new service: ng g s post
  4. Handling Errors Types:
    1. Server is offline
    2. Network is down
    3. Unhandled exceptions
    4. "Not found" errors (404) -- expected error
    5. "Bad request" errors (400) -- expected error
So much has changed with handling errors so my code is noticeably different from what Mosh has in his tutorial due to certain things be deprecated. So, here is my code for my file name "post.service.ts". You can use it as a reference if you're also using Angular version 11+ like me.
import {HttpClient} from '@angular/common/http';
import { Injectable } from '@angular/core';

import {Observable, throwError} from 'rxjs';
import {catchError} from 'rxjs/operators';
import { AppError } from '../common/app-error';
import { NotFoundError } from '../common/not-found-error';

@Injectable({
 providedIn: 'root'
})
export class PostService {
 private url = 'http://jsonplaceholder.typicode.com/posts'

 constructor(private http: HttpClient) { }
 getPost() {
  return this.http.get(this.url);
 }

 createPost(post: any) {
  return this.http.post(this.url, JSON.stringify(post))
 }

 updatePost(post: any) {
  return this.http.patch(this.url + '/' + post.id, JSON.stringify({isRead: true}))
 }

 deletePost(id: number) {
  return this.http.delete(this.url + '/' + id)
  .pipe(catchError(error => {
   if (error.status === 404) 
    return throwError(new NotFoundError());
    
   return throwError(new AppError(error));
  })) 
 }
}

In : angular 


Tags: learning angular  beginner typescript 

About Ninja Space Content


Ninja Space Content I have been building simple websites on my own since 2008 and currently run several websites at the moment, including this one. I used to be an account manager for an affiliate/e-commerce company, helping affiliates grow their sales so I have some knowledge on the business side and client side of affiliate marketing. During the Covid-19 pandemic, I completed a JavaScript coding bootcamp and graduated in Dec 2020. I've been working as a contractor for a few software companies ever since.
Note: links to resources and promoting special deals may allow me to earn a small commission from each sale.