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.
- 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.
- 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.
- To create a new service:
ng g s post
- Handling Errors Types:
- Server is offline
- Network is down
- Unhandled exceptions
- "Not found" errors (404) -- expected error
- "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