What's Angular in the JAMstack?

What's Angular in the JAMstack?

This Angular tutorial explains what JAMstack is and What's Angular in the JAMstack? The JAMstack (JavaScript, API, Markup) is a modern architecture using the technologies that we are used to, it’s been growing in popularity since its conception.

You may have heard about the JAMstack, it’s been growing in popularity since its conception. There are a ton of great articles, videos, and tutorials that explain the JAMstack. I wanted this post to specifically delve into the topic through Angular-colored glasses (which are, of course, rose-colored 🌹).

The JAMstack Explained

The JAMstack is a modern architecture using the technologies that we are used to, and, dare I say, fond of:

  • JavaScript (<– insert Angular here)
  • APIs
  • Markup (<– we can also use Angular here!)

In the JAMstack we orchestrate these technologies to deliver safe, fast, and dynamic sites without relying on web servers.

This is a great way to describe this acronym, but you don’t have to use all of these technologies. The term JAMstack came into existence to help us talk about this architecture that let us remove the complexity of dealing with servers, give us the performance benefits of static sites, but make them dynamic.

In working with the JAMstack best practices you would:

  • 🗄 deliver your site using globally-distributed CDN (Content Delivery Networks) nodes with content dynamically delivered via an API, such as via a CMS (Content Management Services)

  • 🤝 use APIs, serverless functions and webhooks to make your site dynamic, and

  • 🧰 establish a git workflow for a continuous, immutable, and atomic deployment process

Ok, great, but what can you say at the next team meeting? Here are a few high-level benefits this stack gives you:

⛓ Uncouple your frontend from your backend. Tightly-coupled, complicated architectures are harder to scale and harder to maintain or upgrade. By outsourcing your backend you’re also outsourcing your most vulnerable entry points, servers and databases, to teams who can focus on the ever-changing hacking tactics. You don’t have to outsource to gain the benefits of decoupling, you can decouple inside your organization to let teams dedicate their focus to frontend or backend.

👩🏾‍💻 Give your dev team more time and power. Instead of trying to learn and keep up with every technology front & back, your devs can focus on coding the frontend features and experiences your users are asking for. The Git workflow makes jumping into and contributing to a project faster, easier, and less risky (thanks to easy rollbacks). This allows for more freedom to innovate and a lower barrier of entry to contribute.

💰 Step Three: profit. Well, maybe, but more importantly, save money. From big ticket items like infrastructure, security, and backend teams/dev hours to smaller but costly items like license fees, the JAMstack helps alleviate your project budget.

😍 Give your users a better experience. Serving static content from globally-distributed CDNs with re-direct logic will allow you to reliably serve information to your users fast.

We’re Jammin’

I want to do a recap of the JAMstack parts and show you where Angular plays a role. When I saw how these pieces fit together, I definitely had an ‘Ooh! That’s my Jam!’ moment.

J is for JavaScript

The JavaScript in a JAMstack covers the dynamic parts of your app during the request/response cycle, running entirely on the client-side. In our case, we’ll be using Angular as our JavaScript framework but any other framework, library, or plain ol’ lovely JavaScript would work as well. Even if we were to spin up a new Angular application, using ng new, and deploy it using a CDN, we would have ourselves a JAMstack app because we wouldn’t be relying on web servers.

A is for APIs

This is where you feel the JAMstack become truly dynamic. Using API services, third-party libraries or custom serverless functions (lambda functions, Netlify Functions, etc.) you can handle all your server-side and database procedures. To add forms you can drop in Google forms, to add search you can use Algolia, and to work with purchasing you can use the Stripe API. These are just a few examples of the growing ecosystem around JAMstack services.

“Wait, we said no servers! What the what?” was my first thought. What cleared this up for me was realizing we use CDNs not web servers to deliver our apps but tools using servers, like APIs and serverless functions to make our apps dynamic. The term “serverless” is very misleading and does not mean you are no longer using servers. I have a blog post discussing these terms and how servers are and are not used in the JAMstack development process (will link when available 👍).

M is for Markup

Templated, pre-rendered markup makes content delivery super fast. With most other JAMstack apps this content is made using a Static Site Generator (SSG). Currently, there is no go-to SSG for Angular. BUT, this is because the Angular CLI does this already! That’s right, just like every good(?) romantic comedy, what you needed was what you had this whole time but you thought you were just friends. When you run ng build the CLI is composing your files client-side. This is why you can immediately deploy the generated Angular CLI app to Netlify. You can even just rename your dist directory to docs and set a base-hrefto create a GitHub Pages site from your Angular app (there’s also a module: angular-cli-ghpages).

If you take a peek inside your dist folder you’ll see it’s your app’s index.html file (pretty bare bones, usually) with script tags to pull in a bunch of JavaScript files. Although this is all compiled during build, typically generated static sites are HTML pages that are much more readable and SEO-friendly. Guess what, Angular already has that too by using Angular Universal! Yes, your true love that was right under your nose the whole time also makes the most amazing nachos you’ve ever had AND is down with re-listening to the Harry Potter series audiobooks at least once a year. This method isn’t straightforward though. To stick with the rom-com theme, Angular has this hidden like the beauty of the pre-makeover-montage best friend. Your introduction to Angular Universal is:

“This guide describes Angular Universal, a technology that renders Angular applications on the server.”

We want to avoid rendering on the server so this is confusing. If you dig a little deeper you can see that you can use Angular Universal to prerender your content by adding :prerender to your build and serve commands (i.e. ng build:prerender). Then you can add meta and title information with the platform-browser module.

The demand for Angular static site generation is growing. Thanks to Christoph Guttandin we also have a really handy, open-source prerender module, angular-prerender. This module is looking at the information of your site, carrying out the server-side rendering, and merging the output into static content. The Angular team is actively working towards making this process easier from the core. As of writing this post, there is an open pull request on the Angular Universal project to add prerendering scripts to the schematic.

D is for Disclaimer

Wait a second, there’s no ’D’ in JAMstack. You’re so observant! I just wanted to reiterate: JAMstack apps do not have to use all of these technologies. The focus is more on the fact that you’re leveraging tools that take away your app’s dependency on being served with a web sever. This allows you and your team to focus on content your creating and not have to deal with the woes of infrastructure. This is the year of sparking joy, and the JAMstack gives you the opportunity to get back to the joy of unburdened frontend development.

Breaking Down The Best Practices

Thankfully, there are also some best practices to help guide you through JAMstack land. Let’s take a look at them from an Angular point of view.

  • Entire Project on a CDN – A content delivery network allows you to distribute your resources so that they get to your users faster. There are many options for deploying your Angular site to a CDN. (Side note: although Netlify is a great CDN, we also offer tons of other features like analytics, serverless functions, identity, and more to help you with everything from local development to global deployment!)

  • Everything Lives on Git – How ✨magical✨ is version control?! I don’t know how I ever coded without it. The reason it’s a best practice on the JAMstack is not solely for the fact that it lets us revert our code, let alone immutable builds, back to when we didn’t break everything. It is also because having a git workflow makes it easier to share, manage, and contribute to our projects.

  • Modern Build Tools – The technology we use changes at a dizzying pace but we can rely on modern build tools to help us adapt to those changes. Angular already uses webpack through the CLI and you don’t have to make any changes to a standard app.

  • Automated Builds – Since we are creating prebuilt content, only on new builds do we push up new updates. If we create automated builds we can assure that we are getting the most up-to-date content as soon as it’s created. You can do this with webhooks, creating an npm script to use ng deploy every time you run a production build, or, easier yet, connect your project repo to Netlify to trigger a build with each commit.

  • Atomic Deploys – Whenever I think of atomic, my brain only renders this image:

I could never take the heat and always bailed 10 seconds in. Atomic deploys, on the other hand, are in it ‘til the end. They wait until every file is uploaded before launching your site to make sure there are no inconsistencies and no missing information.

  • Instant Cache Validation – In the same respects of atomic deploys, instant cache validation wants to make sure there is no stale information on your page. As soon as the new version of your site is uploaded, the cache is cleared so only the new data is delivered. This is something that can be handled by your CDN.
And I Hope You Like Jammin’ Too

That wraps up this episode of, “What doe this new tech term mean?” I hope this helped you understand the JAMstack better. I’m very excited about this new way of developing and delivering sites. I really do believe it’s putting us on a path towards better performance AND better development experience. The JAMstack has definitely sparked joy in me and renewed my excitement in programming. I’m not only the writer of this post, I’m also a client 😃👍.

I’m very excited to see everything that you create with Angular and the JAMstack. Happy coding!

Originally published by Tara Z. Manicsic at https://www.netlify.com

APIs for Beginners - What is an API? How to use an API?

APIs for Beginners - What is an API? How to use an API?

APIs for Beginners, What exactly is an API? How do you use an API? Learn all about APIs in this full course for beginners. Learn how to use Postman and helper libraries in both JavaScript and Python. Lean how to create a project using an API using both Node.js and Flask. Learn what APIs do, why APIs exist, and the many benefits of APIs. Explore APIs online

APIs for Beginners - What is an API? How do you use an API? Learn all about APIs (Application Programming Interfaces) in this full course for beginners. You will learn what APIs do, why APIs exist, and the many benefits of APIs. APIs are used all the time in programming and web development so it is important to understand how to use them.

You will also get hands-on experience with a few popular web APIs. As long as you know the absolute basics of coding and the web, you'll have no problem following along.

⭐️ Course Contents ⭐️

⭐️ Unit 1 - What is an API
⌨️ Video 1 - Welcome (0:00:00)
⌨️ Video 2 - Defining Interface (0:03:57)
⌨️ Video 3 - Defining API (0:07:51)
⌨️ Video 4 - Remote APIs (0:12:55)
⌨️ Video 5 - How the web works (0:17:04)
⌨️ Video 6 - RESTful API Constraint Scavenger Hunt (0:22:00)

⭐️ Unit 2 - Exploring APIs
⌨️ Video 1 - Exploring an API online (0:27:36)
⌨️ Video 2 - Using an API from the command line (0:44:30)
⌨️ Video 3 - Using Postman to explore APIs (0:53:56)
⌨️ Video 4 - Please please Mr. Postman (1:03:33)
⌨️ Video 5 - Using Helper Libraries (JavaScript) (1:14:41)
⌨️ Video 6 - Using Helper Libraries (Python) (1:24:40)

⭐️ Unit 3 - Using APIs
⌨️ Video 1 - Introducing the project (1:34:18)
⌨️ Video 2 - Flask app (1:36:07)
⌨️ Video 3 - Dealing with API Limits (1:50:00)
⌨️ Video 4 - JavaScript Single Page Application (1:54:27)
⌨️ Video 5 - Moar JavaScript and Recap (2:07:53)
⌨️ Video 6 - Review (2:18:03)

How to send GET Requests to REST API Servers in Angular 9 using HttpClient

How to send GET Requests to REST API Servers in Angular 9 using HttpClient

In this Angular 9 tutorial, you'll learn by example how to send GET requests to REST API servers in your Angular 9 application using HttpClient. Use Angular 9 to build a simple news application that retrieves data from a JSON REST API using the `get()` method of `HttpClient`. Create an Angular 9 project using Angular CLI v9. How to subscribe to the RxJS Observable returned by the `get()` method and how to use the `*ngFor` directive to iterate over fetched data in the template

In this tutorial, you'll learn by example how to send GET requests to REST API servers in your Angular 9 application using HttpClient. We’ll also learn how to use the basic concepts of Angular like components and services and how to use the ngFor directive to display collections of data.

We’ll be consuming a JSON API available from NewsAPI.org

Throughout this tutorial, we are going to build a simple example from scratch using Angular CLI 9 and we’ll see how to use HttpClient to send GET requests to third-party REST API servers and how to consume and display the returned JSON data.

In more details, we'll learn:

  • How to create an Angular 9 project using Angular CLI
  • How to quickly set up routing in our project
  • How to create Angular components
  • How to subscribe to Observables,
  • How to use the ngFor directive in templates to iterate over data.
Prerequisites

Before getting started, you need a few requirements. You need to have the following tools installed on your development machine:

  • Node.js and npm. You can install both of them from the official website.
  • Angular CLI 9 (You can install it from npm using: npm install -g @angular/cli)
Creating an Angular 9 Project

Now let’s create our Angular 9 project. Open a new terminal and run the following command:

$ ng new angular-httpclient-demo

The CLI will prompt you if Would you like to add Angular routing? (y/N), type y. And Which stylesheet format would you like to use? Choose CSS and type Enter.

Next, you can serve your application locally using the following commands:

$ cd ./angular-httpclient-demo
$ ng serve

Your application will be running from http://localhost:4200.

Getting News Data

Before you can fetch the news data from NewsAPI.org which offers a free plan for open source and development projects, you first need to go the register page for getting an API key.

Adding an Angular Service

Next, let’s create a service that will take care of getting data from the news API. Open a new terminal and run the following command:

$ ng generate service api

Setting up HttpClient

Next, open the src/app/app.module.ts file then import HttpClientModule and add it to the imports array:

// [...]
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    // [...]
    HttpClientModule,
  ],
  // [...]
})
export class AppModule {}

That's all, we are now ready to use the HttpClient in our project.

Injecting HttpClient in The Angular Service

Next, open the src/app/api.service.ts file and inject HttpClient via the service constructor:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

  constructor(private httpClient: HttpClient) { }
}

Sending GET Request for Fetching Data

Next, define an API_KEY variable which will hold your API key from the News API:

export class ApiService {
  API_KEY = 'YOUR_API_KEY';

Finally, add a method that sends a GET request to an endpoint for TechCrunch news:

  public getNews(){
    return this.httpClient.get(`https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=${this.API_KEY}`);
  }

That’s all we need to add for the service.

How the HttpClient.get() Method Works

The HttpClient get() method is designed to send HTTP GET requests. The syntax is as follows:

get(url: string, options: {
      headers?: HttpHeaders;
      observe: 'response';
      params?: HttpParams;
      reportProgress?: boolean;
      responseType?: 'json';
      withCredentials?: boolean;
}): Observable<HttpResponse<Object>>;

It takes a REST API endpoint and an optional options object and returns an Observable instance.

Creating an Angular 9 Component

Now, let's create an Angular 9 component for displaying the news data. Head back to your terminal and run the following command:

$ ng generate component news

Injecting ApiService in Your Component

Next, open the src/app/news/news.component.ts file and start by importing ApiService in your component:

import { ApiService } from '../api.service';

Next, you need to inject ApiService via the component's constructor:

import { Component, OnInit } from '@angular/core';
import { ApiService } from '../api.service';
@Component({
  selector: 'app-news',
  templateUrl: './news.component.html',
  styleUrls: ['./news.component.css']
})
export class NewsComponent implements OnInit {

  constructor(private apiService: ApiService) { }
}

Sending the GET Request & Subscribing to The Observable

Next, define an articles variable and call the getNews() method of the API service in the ngOnInit() method of the component:

export class NewsComponent implements OnInit {
  articles;

  constructor(private apiService: ApiService) { }
  ngOnInit() {
    this.apiService.getNews().subscribe((data)=>{
      console.log(data);
      this.articles = data['articles'];
    });
  }
}

This will make sure our data is fetched once the component is loaded.

We call the getNews() method and subscribe to the returned Observable which will send a GET request to the news endpoint.

Displaying Data in The Template with NgFor

Let’s now display the news articles in our component template. Open the src/app/news.component.html file and update it as follows:

<div *ngFor="let article of articles">
  <h2>{{article.title}}</h2>

    <p>
      {{article.description}}
    </p>
    <a href="{{article.url}}">Read full article</a>
</div>

Adding the Angular Component to The Router

Angular CLI 9 has automatically added routing for us, so we don’t need to set up anything besides adding the component(s) to our Router configuration. Open the src/app/app-routing.module.ts file and start by importing the news component as follows:

import { NewsComponent } from './news/news.component';

Next, add the component to the routes array:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { NewsComponent } from './news/news.component';
const routes: Routes = [
  {path:'news', component: NewsComponent}
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

You can now access your component from the /news path.

Conclusion

In this tutorial, we used Angular 9 to build a simple news application that retrieves data from a JSON REST API using the get() method of HttpClient. We’ve seen how to subscribe to the RxJS Observable returned by the get() method and how to use the *ngFor directive to iterate over fetched data in the template. Finally, we’ve seen how we can create an Angular 9 project using Angular CLI v9, how to generate components and services and how to configure routing for the component.

Angular 9 Service Tutorial: Creating API and HttpClient

Angular 9 Service Tutorial: Creating API and HttpClient

In this Angular 9 Service tutorial shows you the Angular Service example, we will create an API with HttpClient service. How to create a Service class and write the APIs in it. We also learned how to access the Service methods and properties in Angular components. Angular Service contains the various methods and functions to manage the data arriving from the server.

In this tutorial, we are going to discuss Angular 8/9 Service. To show you the Angular Service example, we will create API with HttpClient service.

Angular Service contains the various methods and functions to manage the data arriving from the server.

Why Angular Service Class?

  • To handle the features that are separate from components such as authentication, CRUD operations.
  • To share the data among various components in an Angular app.
  • To make the Testing and Debugging simple.
  • To write the re-usable code to centrally organise the application.

Table of Contents

  • What is Angular Service?
  • Set Up Angular CLI
  • Setting Up Angular Project
  • Creating Service Class
  • Creating Methods in Service Class
  • Access Service Methods in Components
  • Conclusion
What is Angular Service?

Most of the time, we get into the situation where we need to use the same code again and again. Using repetitive code in multiple components becomes a headache.

When the size of an Angular application gets bigger, then It almost becomes difficult to manage the code base of our app. In this scenario, the best practice will be to write the reusable code.

To deal with this kind of situation, we can undoubtedly take the help of the Services class in Angular. Its a JavaScript class and includes properties and methods to share the data between unknown components classes.

Set Up Angular CLI

To install the Angular project, you need to have latest version of Angular CLI installed.

npm install -g @angular/[email protected]

In case of error prefix sudo with the above command and provide admin password.

Setting Up Angular Project

Run the below command to install the brand new Angular project.

ng new angular-service-example

Run command to get inside the project folder.

cd angular-service-example

Start the application in the browser.

ng serve --open
Creating Service Class

Our service will contain the create, read, update and delete methods for a demo task management app. To create an Angular Service class, you need to run the following command via Angular CLI.

ng generate service crud

Above command creates the following files in the src/app folder.

# src/app/crud.service.spec.ts

# src/app/crud.service.ts

Here, is the file crud.service.ts file we generated for Angular Service example.

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})

export class CrudService {

  constructor() { }

}

@Injectable(): Decorator that marks a class as available to be provided and injected as a dependency.

providedIn: Injectors make the communication with injectable that is something based on with @NgModule or other InjectorType, even by specifying that this injectable should be provided in the ‘root’ injector.

Next, we need to import the Service Class in the app.module.ts, and also register the service class in the providers array.

// Service class
import { CrudService } from './crud.service';

@NgModule({
  declarations: [...],
  imports: [...],
  providers: [CrudService],
  bootstrap: [...]
})

Importing and registering the service class in Angular’s main app module means that, service class is available throughout the application.

Creating Methods in Service Class

In this part of the tutorial, we will write API in Angular Service Class. In the below example we wrote the CRUD operations using the HttpClient service.

To make these methods work you also need to import and register HttpClientModule in the main app module file.

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    HttpClientModule
   ]
})

In the API section you need to pass the API URL in order to make this API work.

import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})

export class CrudService {

  apiUrl: string = 'enter-your-api-url';
  headers = new HttpHeaders().set('Content-Type', 'application/json');

  constructor(private http: HttpClient) { }

  // Create
  createTask(data): Observable<any> {
    let API_URL = `${this.apiUrl}/create-task`;
    return this.http.post(API_URL, data)
      .pipe(
        catchError(this.error)
      )
  }

  // Read
  showTasks() {
    return this.http.get(`${this.apiUrl}`);
  }

  // Update
  updateTask(id, data): Observable<any> {
    let API_URL = `${this.apiUrl}/update-task/${id}`;
    return this.http.put(API_URL, data, { headers: this.headers }).pipe(
      catchError(this.error)
    )
  }

  // Delete
  deleteTask(id): Observable<any> {
    var API_URL = `${this.apiUrl}/delete-task/${id}`;
    return this.http.delete(API_URL).pipe(
      catchError(this.error)
    )
  }

  // Handle Errors 
  error(error: HttpErrorResponse) {
    let errorMessage = '';
    if (error.error instanceof ErrorEvent) {
      errorMessage = error.error.message;
    } else {
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    console.log(errorMessage);
    return throwError(errorMessage);
  }

}
Access Service Methods in Components

To access the Service methods, we need to import the Service in the component file, let’s import the CrudService class in the app.component.ts.

import { CrudService } from './crud.service';

Next, we need to follow the dependency injection pattern and inject the Service class inside the constructor.

export class AppComponent {

  constructor(private crudService: CrudService){}

}

Next, we can easily access all the CrudService methods, and we are using the ngOnInit() lifecycle hook to access the showTask() method of Angular Service class.

import { Component, OnInit } from '@angular/core';
import { CrudService } from './crud.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {

  constructor(private crudService: CrudService) { }

  ngOnInit() {
    console.log(this.crudService.showTasks);
  }

}

Conclusion

Now, Angular 8/9 Service Tutorial is completed with examples. In this tutorial, we looked at how to create a Service class and write the APIs in it. We also learned how to access the Service methods and properties in Angular components. I hope you liked this tutorial. Please share this tutorial with others.