Ninja Space Content Blog

Week Seven of Learning Angular

Posted by Ninja Space Content on Tuesday, May 11, 2021 Under: angular
I'm officially 30% through Programming with Mosh' Angular tutorial! This week I am learning to pull data using http services with Angular. Read my week-to-week down notes and thoughts as I am learning Angular through an online self-pace tutorial.

I'm already encountering version errors at the beginning. Firstly, HttpModule cannot be imported from @angular/http as it has been deprecated and here are the changes I had to make!

In Mosh' tutorial, he started out with instructing that we need to add the following for the app.module.ts file:

import {HttpModule} from '@angular/http'; and then under imports, add: HttpModule to the array but that created errors for me.

So, I made the following changes in order to compile without errors:

import { HttpClientModule } from '@angular/common/http'; and then under imports, it should be HttpClientModule

Secondly, in Mosh's tutorial, in the posts.component.ts file, he instructed to add
import {Http} from '@angular/http'; and in the constructor with 
constructor(http: Http) That's deprecated so I had to change to the following: import {HttpClient} from '@angular/common/http'; and constructor(http: HttpClient).

Type any[ ] for http class
I spent a good 30 minutes debugging this because I'm learning from Programming with Mosh's tutorial and he used an older TypeScript version and I am using version 11.2.8. In Mosh' tutorial, he initialized posts like this: posts: any[];but I actually had to initialize it like this: posts: any = [];. Otherwise, you'll keep this this error in your terminal: Type 'Object' is missing the following properties from type 'any[]': length, pop, push, concat, and 26 more. Here is my full working code for my version to pull data:

import {HttpClient} from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.css']
})
export class PostsComponent {
  posts: any = [];
 
  constructor(http: HttpClient) { 
   
    http.get('http://jsonplaceholder.typicode.com/posts')
    .subscribe(response => {
      console.log(response);
      this.posts = response;
    });
  }
  ngOnInit(): void {
  }
}

Notably, from above, I also didn't have to call the json function to get the json response as it seems to be doing that automatically now under the hood for my version. Mosh had to in his older TypeScript version. Yay, for efficiency!

I also want to say that I love how much time Mosh spends on analyzing data like going into the Network data because I didn't get to go too deep with that in my coding bootcamp days so not having a time-sensitive project coming up lets me really get in deep into this type of response data.

Sample Create, Update and Delete Functions
I know this will be very handy for me later so here were the Create, Update and Delete functions that I created under my posts.component.ts file: 
import {HttpClient} from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
 selector: 'posts',
 templateUrl: './posts.component.html',
 styleUrls: ['./posts.component.css']
})
export class PostsComponent {
 posts: any = [];
 private url = 'http://jsonplaceholder.typicode.com/posts'

 constructor(private http: HttpClient) { 
 
 http.get(this.url)
 .subscribe(response => {
 console.log(response);
 this.posts = response;
 });
 }

 createPost(input: HTMLInputElement) {
 let post: any = {title: input.value}
 input.value = '';

 this.http.post(this.url, JSON.stringify(post))
 .subscribe(response => {
 this.posts.splice(0,0, post)
 console.log(response)
 });
 }

 updatePost(post: any) {
 this.http.patch(this.url + '/' + post.id, JSON.stringify({isRead: true}))
 .subscribe(response => {
 console.log(response)
 })
 }

 deletePost(post:any) {
 this.http.delete(this.url + '/' + post.id)
 .subscribe(response => {
 let index = this.posts.indexOf(post);
 this.posts.splice(index, 1)
 })
 }

 ngOnInit(): void {
 }

}
Here's my code from the posts.component.html file:

<input 
(keyup.enter)="createPost(title)" #title
type="text" class="form-control">
<ul class="list-group">
    <li 
    *ngFor = "let post of posts"
    class="list-group-item">
    <button 
        (click)="deletePost(post)"
        class="btn btn-default btn-sm">Delete</button>
    {{post.title}}
    <button 
        (click)="updatePost(post)"
        class="btn btn-default btn-sm">Update</button>
</li>
</ul>

In : angular 


Tags: learning angular  http services angular example 

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. Most recently, I decided to complete a JavaScript coding bootcamp and graduated in Dec 2020.
Note: links to resources and promoting special deals may allow me to earn a small commission from each sale.
Work Station Accessories