How to Update Angular Projects to the Latest Version
Key Points
- Before trying to update, make sure that the latest version of Angular CLI is installed by running
npm install -g @angular/cli@latest
. - Use the Angular Update Guide to determine the specific steps to update from the current Angular version to the required version and adjust it according to the complexity of the application.
- Replace
HttpModule
withHttpClientModule
to take advantage of the new HttpClient's automatic JSON processing and support for HTTP interceptors. - Enhance tree-shaking and reduce package size by importing them from
rxjs/operators
and applying them in the.pipe()
method to using RxJS pipetable operators.
After the - is updated, verify the functionality and Angular version of the application by running
ng serve
and checking theng-version
attribute in the app-root element. - Follow the official Angular blog and change log for new versions and updates to maintain your application with the latest improvements and features.
This article will explain how to update Angular projects to the latest version.
This article is part 6 of the SitePoint Angular 2 tutorial, which describes how to create a CRUD application using the Angular CLI.
- Part 0 — The Final Angular CLI Reference Guide
- Part 1 — Getting Up and Running the First Version of Our Todo Application
- Part 2 — Create separate components to display Todo list and individual Todo
- Part 3 — Update the Todo service to communicate with the REST API
- Part 4 — Using Angular Router to parse data
- Part 5 — Add Authentication to Protect Private Content
- Part 6 — How to update Angular projects to the latest version
In Part 1, we learned how to get our Todo application up and run and deploy it to GitHub Pages. This works great, but unfortunately the whole application is stuffed into a component.
In Part 2, we examined a more modular component architecture and learned how to break this single component into a structured, smaller component tree that is easier to understand, reuse, and maintain.
In Part 3, we updated the application to communicate with the REST API backend using RxJS and Angular's HTTP service.
In Part 4, we introduce Angular Router and learn how routers update our applications when browser URL changes, and how we use the router to parse data from the backend API.
In Part 5, we added authentication to the application and learned how to protect various parts of the application from unauthorized access.
Don't worry! You do not need to follow Part 1, 2, 3, 4, or 5 of this tutorial to understand Part 6. You can simply take a copy of our code base, look at the code for Part 5, and use it as a starting point. This will be explained in more detail below.
Upload and run
To start updating Angular's target, make sure the latest version of Angular CLI is installed. If not, you can install it with the following command:
npm install -g @angular/cli@latest
If you need to delete the previous version of Angular CLI, you can:
npm uninstall -g @angular/cli angular-cli npm cache clean npm install -g @angular/cli@latest
, you need a copy of the code for Part 5. This is available on GitHub. Each post in this series has a corresponding tag in the repository, so you can switch back and forth between different states of this app.
The code we used at the end of Part 5, and the code we started with in this article, is marked part-5. The code we used to end this article is marked part-6.
You can treat tags as an alias for a specific commit ID. You can switch between them using git checkout. You can read more about it here.
So, to get up and running (install the latest version of Angular CLI), we will do the following:
git clone git@github.com:sitepoint-editors/angular-todo-app.git cd angular-todo-app git checkout part-5 npm install ng serve
Then visit the https://www.php.cn/link/d111f133fa0ea545d48291f9b0a72b2d Todo application.
Update Angular: Our Attack Plan
In this article, when we update Angular, we will learn the following:
- How does Angular version work
- Where can I find instructions on how to update Angular
- How to update our code from Angular 4 to Angular 5 (At the time of writing, Angular 5 is the latest version).
At the end of this article, you will learn about:
- The fundamental meaning of a specific Angular version
- Where can I find exact instructions on how to update Angular applications
- How to determine which code changes are required for Angular 5 (if any).
Let's get started!
The meaning of Angular version
In order to support a thriving ecosystem, Angular needs to be both stable and developing.
On the one hand, Angular is designed to provide maximum stability for mission-critical applications. On the other hand, it needs to be adapted and evolved to support the latest changes in Web technology.
Therefore, the Angular team decided to use time-based release cycles and semantic versioning.
The time-based release cycle means we can expect new Angular versions (Angular 5, Angular 6, Angular 7, etc.) to appear every few weeks or months.
Semantic versioning means that Angular's version number allows us to predict whether it will break our application if we upgrade to it.
Essentially, the semantic version looks like this: major version. minor version. revision.
Therefore, the primary version value of version v1.3.8 is 1, the secondary version value is 3, and the revision value is 1.
When a new version is released, the new version implicitly indicates the type of changes made to the code.
When adding semantic version, the following rules are applied:
-
Each increment will be numerical incremented in increments of 1.
-
Revised version will be added when fixing errors and the code remains backward compatible:
npm install -g @angular/cli@latest
Copy after loginCopy after loginCopy after loginCopy after login -
When adding features and the code remains backward compatible, a subversion will be added and the revision will be reset to zero:
npm uninstall -g @angular/cli angular-cli npm cache clean npm install -g @angular/cli@latest
Copy after loginCopy after loginCopy after loginCopy after login -
When implementing changes that cause the code to become backwards incompatible (also known as a major change), the major version is added and the minor version and revision are reset to zero:
git clone git@github.com:sitepoint-editors/angular-todo-app.git cd angular-todo-app git checkout part-5 npm install ng serve
Copy after loginCopy after loginCopy after loginCopy after login
If you are not familiar with semantic versioning, be sure to check out this simple semantic versioning guide.
The Angular team combines semantic versioning with time-based release cycles, aiming to:
- A new revision is released every week
- A new subversion is released every month
- A new major release is released every 6 months
The release plan is not set in stone, as there may be holidays or special events, but it is a good indicator of what we can expect upcoming releases.
You can follow the official Angular blog and official change log to stay up to date with the latest developments.
A huge benefit of semantic versioning is that we can safely update Angular applications with revisions or subversions without worrying about breaking our applications.
But what happens if a new major version appears?
Angular Update Guide
We have learned that major versions may bring significant changes. So, if we update it, how do we know if our existing applications will break?
One way is to read the official change log and view the change list.
An easier way is to use the Angular update guide to update Angular. You can select the current Angular version and the version you wish to upgrade to, and the application will tell you the exact steps you need to take:
For our Angular Todo application, we want to upgrade from Angular 4.0 to Angular 5.0.
Let's choose the application complexity levelAdvanced so that we see all possible measures we need to take:
We have obtained a complete overview of all the steps we need to take to update our application.
Great!
Before update
Before update The list contains 12 items. No one project is available for our Angular Todo application, so we can safely move on to the next step.
Update period
In the update period list, only the last item applies to our application. We need to update our dependencies, so let's run the suggested command in the root of the project:
npm install -g @angular/cli@latest
Because we updated the Angular CLI to the latest version in the up and running section, we also updated our local version:
npm uninstall -g @angular/cli angular-cli npm cache clean npm install -g @angular/cli@latest
To verify that our application is running correctly, we run:
git clone git@github.com:sitepoint-editors/angular-todo-app.git cd angular-todo-app git checkout part-5 npm install ng serve
If ng serve
fails to start, try deleting your node_modules
directory and package-lock.json
file and then run npm install
to recreate the clean node_modules
directory and package-lock.json
file.
After update
After the update list contains four items, the first and last ones apply to our application:
- Switch from HttpModule to HttpClientModule
- Import the RxJS operator from rxjs/operators and use the RxJS pipeline operator
Let's solve them one by one.
Switch from HttpModule to HttpClientModule
The Angular update guide tells us that we should switch from HttpModule to HttpClientModule.
If we check the release notes for Angular version 5.0.0, we will learn that Angular 4.3 and later comes with a new HttpClient that automatically handles JSON responses and supports HTTP interceptors.
It states that to update our code, we must replace HttpModule with HttpClientModule, inject the HttpClient service and delete all map(res => res.json())
calls, because the new HttpClient automatically parses the JSON response.
Let's open src/app/app.module.ts
and replace HttpModule:
<code> v0.0.3 // 修复错误前 v0.0.4 // 修复错误后</code>
Using HttpClientModule:
<code> v0.2.4 // 添加新功能前 v0.3.0 // 添加新功能后</code>
Next, we have to use the HttpClient service instead of the Http service and delete all map(res => res.json())
calls in the code, because the new HttpClient will automatically parse the response for us.
In Part 3, we are concentrating all the HTTP-related code in a service called ApiService, and we are now enjoying the benefits of this approach.
So we only need to update one file, so let's open src/app/api.service.ts
and replace:
<code> v7.3.5 // 实现向后不兼容的更改前 v8.0.0 // 实现向后不兼容的更改后</code>
Usage:
$ npm install @angular/{animations,common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router}@'^5.0.0' typescript@2.4.2 rxjs@'^5.5.2' $ npm install typescript@2.4.2 --save-exact
We replace the old class in HttpModule with the new class in HttpClientModule.
More specifically, we replace:
import { Http, Headers, RequestOptions, Response } from '@angular/http';
forimport { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
- Line 81:
Response
forHttpErrorResponse
- Line 90:
Headers
forHttpHeaders
- Line 93:
return new RequestOptions({ headers });
forreturn { headers };
If we run:
npm install -g @angular/cli@latest
and navigate the browser to https://www.php.cn/link/03e03424a898e574153a10db9a4db79a HttpClientModule.
It's time to solve Project 2: Import the RxJS operator from rxjs/operators and use the RxJS pipeline operator.
Using RxJS pipeline operator
Angular 5 has been updated to use RxJS 5.5.2 or later.
Starting with version 5.5, RxJS comes with a pipeable operator. The official document says:
Pipeable operator is any function that returns a function with the following signature:
<T, R>(source: Observable<T>) => Observable<R>
…
You extract any required operators from a position (under
rxjs/operators
(plural!). It is also recommended to directly extract the Observable creation method you need, as shown below, the scope of use:
npm uninstall -g @angular/cli angular-cli npm cache clean npm install -g @angular/cli@latestCopy after loginCopy after loginCopy after loginCopy after login
Although this sounds complicated, it basically means where we used chained methods before:
git clone git@github.com:sitepoint-editors/angular-todo-app.git cd angular-todo-app git checkout part-5 npm install ng serve
We should now import operators from rxjs/operators
and apply them using the .pipe()
method:
<code> v0.0.3 // 修复错误前 v0.0.4 // 修复错误后</code>
The main benefits of pipeable operators are:
- They are tree-shaking, allowing the tool to reduce the size of the application package by removing unused code.
- They are normal functions, so we can easily create our own custom pipeable operators.
.pipe()
method minimizes the impact on our code.
There are two projects in our application that need to be refactored: our ApiService and TodosComponent.
First, let's open src/app/api.service.ts
to update our ApiService:
<code> v0.2.4 // 添加新功能前 v0.3.0 // 添加新功能后</code>
We import the rxjs/operators
pipetable operator from map
and update all occurrences of map(fn)
to pipe(map(fn))
.
Next, let's open src/app/todos/todos.component.ts
to apply the same changes to TodosComponent:
<code> v7.3.5 // 实现向后不兼容的更改前 v8.0.0 // 实现向后不兼容的更改后</code>
Similarly, we import the rxjs/operators
pipetable operator from map
and update map(fn)
to pipe(map(fn))
.
That's it! The chained operators in our application have been replaced by pipeable operators, just as the Angular update guide directs us to do.
If we navigate to https://www.php.cn/link/668c7d9d4728fc9eebbe7a8202c95c26.
To verify that we are indeed running Angular 5, we can open the Element Inspector:
Angular Adds the ng-version
property to app-root
with the value of the version it is running. We see ng-version="5.2.9"
, indicating that we are running Angular 5.2.9.
The mission is completed! Our application has been successfully upgraded to Angular 5.2.9.
We cover a lot, so let's review what we've learned.
Summary
In the first article, we learned how:
- Initialize our Todo application using the Angular CLI
- Create a Todo class to represent a single todo
- Create a TodoDataService service to create, update and delete todo
- Use the AppComponent component to display the user interface
- Deploy our applications to GitHub Pages.
In the second article, we refactored the AppComponent to delegate most of its work to:
- A TodoListComponent to display the todo list
- A TodoListItemComponent to display a single todo
- A TodoListHeaderComponent to create a new todo
- A TodoListFooterComponent to show how many todos are left.
In the third article, we learned how:
- Create a simulated REST API backend
- Storing API URLs as environment variables
- Create an ApiService to communicate with the REST API
- Update TodoDataService to use the new ApiService
- Update AppComponent to handle asynchronous API calls
- Create an ApiMockService to avoid actual HTTP calls when running unit tests.
In the fourth article, we learned:
- Why application may need routing
- What is JavaScript router?
- What is Angular Router, how it works and what it can do for you
- How to set up Angular router and configure the routing of your application
- How to tell Angular router where to place components in the DOM
- How to handle unknown URL gracefully
- How to use a parser to make Angular router parse data.
In the fifth article, we learned:
- Difference between cookies and tokens
- How to create an AuthService to implement authentication logic
- How to create a SessionService to store session data
- How to create a login form using Angular reactive form
- How to create a route guard to prevent unauthorized access to the part of the application
- How to send a user's token as an authorization header to your API in an HTTP request
- Why you should never send a user's token to a third party.
In this article on how to update Angular, we learned:
- How does Angular version work
- The meaning of semantic version number
- How semantic versioning protects us from blindly introducing major changes into our application
- How the Angular Update Guide helps us find detailed instructions on how to update Angular
- How to replace HttpModule with HttpClientModule
- How to update our RxJS code using pipeable operators
-
ng-version
Properties let us verify which version of Angular we are running.
In the upcoming release, the Angular CLI will introduce the ng update
command to help update Angular applications. Once more details are available, we will provide a follow-up article on how this new command can make our lives easier.
Before this, you can use this article as a guide on how to update Angular applications to the latest version.
All the code in this article can be found on GitHub.
I wish you all the best!
FAQs about updating Angular projects (FAQ)
What are the prerequisites for updating my Angular project?
Before you start updating your Angular project, make sure that the latest versions of Node.js and npm are installed. You can check your version by running node -v
and npm -v
in the terminal. If you don't have them installed, or your version is expired, please visit the official Node.js website to download and install them. Also, make sure your Angular CLI is the latest version. You can update it by running npm install -g @angular/cli
in the terminal.
How to update my Angular project to a specific version?
To update your Angular project to a specific version, you can use the ng update
command followed by the package name and version number. For example, if you want to update to Angular 9, you will run ng update @angular/core@9 @angular/cli@9
in your terminal. Remember to submit any changes to the project before running the update command to avoid losing any work.
What should I do if I encounter an error during the update process?
If you encounter an error during the update process, try to understand the error message first. It usually contains clues about where it went wrong. If you can’t solve the problem, consider seeking help from the Angular community. There are many experienced developers on sites like StackOverflow that can help you troubleshoot problems. Remember to provide as much detail about your problem as possible, including error messages and steps you took before you encounter an error.
How to downgrade my Angular project to a previous version?
Downgrading an Angular project to a previous version can be a bit tricky, as it usually is more than just changing the version number in the package.json
file. You may also need to downgrade other dependencies and tweak your code to make it compatible with older versions. If you need a downgrade, consider seeking help from the Angular community or hiring a professional developer to ensure the process goes smoothly.
How to track changes in each Angular update?
The Angular team provides detailed release notes for each update on its official website. These instructions include a summary of changes introduced in the update, bug fixes, and new features. You can also use the --dry-run
command with the ng update
option to see what changes will be made in your project without actually applying them.
How to test my Angular project after update?
After updating the Angular project, be sure to thoroughly test it to make sure everything still works as expected. You can use the built-in testing tools of the Angular CLI, such as Karma and Protractor, to run unit tests and end-to-end tests on your project. If you have any problems, refer to the error messages and the Angular documentation for how to resolve them.
How often should I update the Angular project?
The frequency of updates depends on the specific requirements of the project and the stability of the Angular version you are using. However, it is usually best to use the latest stable version to keep updating to take advantage of the latest features and improvements. Remember to thoroughly test your project after each update to make sure everything still works as expected.
Can version be skipped when updating Angular projects?
Yes, versions can be skipped when updating Angular projects. However, it is recommended to update one major version at a time to avoid potential problems. If you are updating from a very old version, consider seeking help from the Angular community or hiring a professional developer to make sure the process goes smoothly.
What are the benefits of updating Angular projects?
Update the Angular project to benefit from the latest features, improvements, and bug fixes. It also helps keep your project safe and compatible with other modern technologies. However, remember to thoroughly test your project after each update to make sure everything still works as expected.
How to automate the update process of Angular projects?
You can use continuous integration (CI) tools such as Jenkins or Travis CI to automate the update process of Angular projects. These tools can automatically run the ng update
command and your tests whenever you push changes to the repository. This can help ensure that your project is always up to date and works properly.
The above is the detailed content of How to Update Angular Projects to the Latest Version. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...
