Reader small image

You're reading from  Angular for Enterprise Applications - Third Edition

Product typeBook
Published inJan 2024
Reading LevelExpert
PublisherPackt
ISBN-139781805127123
Edition3rd Edition
Languages
Right arrow
Author (1)
Doguhan Uluca
Doguhan Uluca
author image
Doguhan Uluca

Doguhan Uluca is a Principal Fellow at Excella in Washington, D.C., where he leads strategic initiatives and delivers critical systems. He has technical expertise in usability, mobility, performance, scalability, cybersecurity, and architecture. He is the author of the Angular for Enterprise Application Development books, has spoken at over 30 conferences, and is an Angular GDE Alumni. Doguhan has delivered solutions for Silicon Valley startups, Fortune 50 companies, and the U.S. Federal Government, and he is passionate about contributing to open-source projects and teaching.
Read more about Doguhan Uluca

Right arrow

Forms, Observables, Signals, and Subjects

In this chapter, we’ll work on a simple weather app, LocalCast Weather, using Angular and a third-party web API from OpenWeatherMap.org. The source code for this project is provided on GitHub at https://github.com/duluca/local-weather-app, including various stages of development in the projects folder.

If you’ve never used Angular before and need an introduction to Angular essentials, I recommend checking out What is Angular? on Angular.dev at https://angular.dev/overview and going through the Learn Angular Tutorial at https://angular.dev/tutorials/learn-angular.

Feeling brave? Just type the following into your terminal:

$ npm create @angular

LocalCast Weather is a simple app that demonstrates the essential elements that make up an Angular application, such as components, standalone components, modules, providers, pipes, services, RxJS, unit testing, e2e using Cypress, environment variables, Angular...

Technical requirements

The most up-to-date versions of the sample code for the book are on GitHub at the repository linked shortly. The repository contains the final and completed state of the code. You can verify your progress at the end of this chapter by looking for the end-of-chapter snapshot of code under the projects folder.

For Chapter 2:

  1. Clone the https://github.com/duluca/local-weather-app repo.
  2. Execute npm install on the root folder to install dependencies.
  3. The beginning state of the project is reflected at:
    projects/stage5
    
  4. The end state of the project is reflected at:
    projects/stage6
    
  5. Add the stage name to any ng command to act only on that stage:
    npx ng build stage6
    

Note that the dist/stage6 folder at the root of the repository will contain the compiled result.

Beware that the source code provided in the book and the version on GitHub are likely to be...

Great UX should drive implementation

Creating an easy-to-use and rich User Experience (UX) should be your main goal. You shouldn’t pick a design just because it’s easiest to implement. However, often, you’ll find a great UX that is simple to implement in the front end of your app but a lot more difficult on the back end. Consider google.com’s landing page:

A screenshot of a google search  Description automatically generated with medium confidence

Figure 2.2: Google’s landing page

In this context, Google Search is just a simple input field with two buttons. Easy to build, right? That simple input field unlocks some of the world’s most sophisticated and advanced software technologies backed by a global infrastructure of custom-built data centers and Artificial Intelligence (AI). It is a deceptively simple and insanely powerful way to interact with users. You can augment user input by leveraging modern web APIs like GeoLocation and add critical context to derive new meaning from user input. So, when the user types in Paris...

Reactive versus template-driven forms

Now, we’ll implement the search bar on the home screen of the application. The next user story states Display forecast information for current location, which may be taken to imply an inherent GeoLocation functionality. However, as you may note, GeoLocation is a separate task. The challenge is that with native platform features such as GeoLocation, you are never guaranteed to receive the actual location information. This may be due to signal loss issues on mobile devices, or the user may simply refuse to give permission to share their location information.

First and foremost, we must deliver a good baseline UX and implement value-added functionality such as GeoLocation only afterward. In stage5, the status of the project is represented on the Kanban board, as captured in the following snapshot:

A screenshot of a chat  Description automatically generated with medium confidence

Figure 2.3: GitHub project Kanban board

We’ll implement the Add city search capability card (which captures a user story...

Component interaction with BehaviorSubject

To update the current weather information, we need the citySearch component to interact with the currentWeather component. There are four main techniques to enable component interaction in Angular:

  • Global events
  • Parent components listening for information bubbling up from children components
  • Sibling, parent, or children components within a module that works off of similar data streams
  • Parent components passing information to children components

Let’s explore them in detail in the following sections.

Global events

This technique has been leveraged since the early days of programming in general. In JavaScript, you may have achieved this with global function delegates or jQuery’s event system. In AngularJS, you may have created a service and stored variables within it.

In Angular, you can still create a root-level service, store values in it, use Angular’s EventEmitter class...

Managing subscriptions

Subscriptions are a convenient way to read a value from a data stream for your application logic. If unmanaged, they can create memory leaks in your application. A leaky application will consume ever-increasing amounts of RAM, eventually leading the browser tab to become unresponsive, leading to a negative perception of your app and, even worse, potential data loss, which can frustrate end users.

The source of a memory leak may not be obvious. In CurrentWeatherComponent, we inject WeatherSevice to access the value of BehaviorSubject, currentWeather$. If we mismanage subscriptions,currentWeather$, we can end up with leaks in the component or the service.

Lifecycle of services

By default, Angular services are shared instance services or singletons automatically registered to a root provider. This means that, once created in memory, they’re kept alive as long as the app or feature module they’re a part of remains in memory. See the following...

Coding in the reactive paradigm

As covered in Chapter 1, Angular’s Architecture and Concepts, we should only subscribe to an observable stream to activate it. If we treat a subscribe function as an event handler, we implement our code imperatively.

Seeing anything other than an empty subscribe() call in your code base should be considered a red flag because it deviates from the reactive paradigm.

In reactive programming, when you subscribe to an event in a reactive stream, you shift your coding paradigm from reactive programming to imperative programming. There are two places in our application where we subscribe, one in CurrentWeatherComponent, and the other in CitySearchComponent.

Let’s start by fixing CurrentWeatherComponent so we don’t mix paradigms.

Binding to an observable with an async pipe

Angular has been designed to be an asynchronous framework from the ground up. You can get the most out of Angular by staying in the reactive...

Chaining API calls

Currently, our app can only handle 5-digit numerical postal or zip codes from the US. A postal code such as 22201 is easy to differentiate from a city name with a simplistic conditional such as typeof search === 'string'. However, postal codes can vary widely from country to country, the UK being a great example, with postal codes such as EC2R 6AB. Even if we had a perfect understanding of how postal codes are formatted for every country, we still couldn’t ensure that the user didn’t fat-finger a slightly incorrect postal code. Today’s sophisticated users expect web applications to be resilient toward such mistakes. However, as web developers, we can’t be expected to code up a universal postal code validation service by hand. Instead, we need to leverage an external service before we send our request to OpenWeatherMap APIs. Let’s explore how we can chain back-to-back API calls that rely on each other.

After...

Using Angular Signals

A signal is a reactivity primitive that keeps track of its value changing over time. Angular Signals implements this primitive to granularly sync the application state with the DOM. By focusing on granular changes in state and only the relevant DOM nodes, the number and severity of change detection operations are significantly reduced. As covered in Chapter 1, Angular’s Architecture and Concepts, change detection is one of the most expensive operations that the Angular framework performs. As an app grows in complexity, change detection operations may be forced to traverse or update larger parts of the DOM tree. As the number of interactive elements increases in your app, change detection events occur more frequently. App complexity combined with the frequency of events can introduce significant performance issues, resulting in slow or choppy rendering of the app. Usually, there’s no quick fix for a problem like this. So, it is critical to understand...

Generating apps with ChatGPT

Let’s see what result we get if we ask ChatGPT to generate a weather app. In August 2023, I asked ChatGPT to generate a weather app using GPT-4 with the CodeInterpreter plugin. I gave it the following prompt:

Write an Angular app that displays real-time weather data from openweathermap.org APIs, using Angular Material, with a user input that accepts city name, country, or postal code as input.

After making a few minor corrections, this is the result I got:

A screenshot of a computer  Description automatically generated

Figure 2.11: ChatGPT weather app – August 2023

ChatGPT created a very simple and straightforward app for me, with a weather-display component using two-way binding for the input field. The service call was correctly implemented in a dedicated weather service triggered by the Fetch Weather button. To achieve similar results to the LocalCast app we built, we would have to provide a prompt with far more technical details. Non-technical people won’t know...

Summary

In this chapter, you learned how to create search-as-you-type functionality using MatInput, validators, reactive forms, and data-stream-driven handlers. You became aware of two-way binding and template-driven forms. You also learned about different strategies to enable inter-component interactions and data sharing. You dove into understanding how memory leaks can be created and the importance of managing your subscriptions.

You can now differentiate between imperative and reactive programming paradigms and understand the importance of sticking with reactive programming where possible. Finally, you learned how to implement sophisticated functionality by chaining multiple API calls together. You learned about the signal primitive and how you can use it to build simpler and more performant applications.

LocalCast Weather is a straightforward application that we used to cover the basic concepts of Angular. As you saw, Angular is great for building such small and dynamic...

Exercises

After completing the Support international zip codes feature, did we switch coding paradigms here? Is our implementation above imperative, reactive, or a combination of both? If our implementation is not entirely reactive, how would you implement this function reactively? I’ll leave this as an exercise for the reader.

Don’t forget to execute npm test, npm run e2e, and npm run test:a11y before moving on. It is left as an exercise for the reader to fix the unit and end-to-end tests.

Visit GitHub to see the unit tests I implemented for this chapter at https://github.com/duluca/local-weather-app/tree/master/projects/stage6.

Questions

Answer the following questions as best as possible to ensure you’ve understood the key concepts from this chapter without googling anything. Do you know if you got all the answers right? Visit https://angularforenterprise.com/self-assessment for more:

  1. What is the async pipe?
  2. Explain how reactive and imperative programming is different and which technique we should prefer.
  3. What is the benefit of BehaviorSubject, and what is it used for?
  4. What are memory leaks and why should they be avoided?
  5. What is the best method for managing subscriptions?
  6. How are Angular signals different than RxJS streams?
  7. What are ways you can use Angular Signals to simplify your application?
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Angular for Enterprise Applications - Third Edition
Published in: Jan 2024Publisher: PacktISBN-13: 9781805127123
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Doguhan Uluca

Doguhan Uluca is a Principal Fellow at Excella in Washington, D.C., where he leads strategic initiatives and delivers critical systems. He has technical expertise in usability, mobility, performance, scalability, cybersecurity, and architecture. He is the author of the Angular for Enterprise Application Development books, has spoken at over 30 conferences, and is an Angular GDE Alumni. Doguhan has delivered solutions for Silicon Valley startups, Fortune 50 companies, and the U.S. Federal Government, and he is passionate about contributing to open-source projects and teaching.
Read more about Doguhan Uluca