Home > Web Front-end > JS Tutorial > body text

Through a practical combat, let's see how PWA is applied to Angular projects

青灯夜游
Release: 2022-04-08 20:31:47
forward
1968 people have browsed it

This article will introduce you to Angular PWA Progressive Web Application, share a practical experience, and see how PWA is applied to Angular projects. I hope it will be helpful to everyone!

Through a practical combat, let's see how PWA is applied to Angular projects

PWA has the following advantages:

  • Availability in no-connection (offline) state
  • Fast loading speed
  • Screen shortcut

If circumstances permit, it is still recommended that you use it in projects to improve performance and user experience.

For more detailed instructions, please view MDN PWA. Talk is Cheap Next, let’s see the effect in practice. [Related tutorial recommendations: "angular tutorial"]

1 Preparation work

npm i -g @angular/cli@latest
ng new pwa-demo
# npm i -g json-server
# npm i -g http-server
Copy after login

Through a practical combat, lets see how PWA is applied to Angular projects

Modifypackage.json It is convenient for us to start the project

{
  ....,
  "scripts": {
    ...,
    "json": "json-server data.json -p 8000",
    "build:pwa": "ng build",
    "start:pwa": "http-server -p 8001 -c-1 dist/pwa-demo"
  }
}
Copy after login

Create a new data.json file to simulate the data, just put it in the root directory

{
  "posts": [{ "id": 1, "title": "json-server", "author": "typicode" }],
  "comments": [{ "id": 1, "body": "some comment", "postId": 1 }],
  "profile": { "name": "typicode" }
}
Copy after login

2 Write a small demo to simulate the future Get the data

ng g s services/data
Copy after login
// data.service.ts
// 记得在 app.module.ts 中引入 HttpClientModule
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  dataUrl = 'http://localhost:8000/posts';

  constructor(private http: HttpClient) {}

  // 实际项目中最好别用 any,可以根据返回的数据类型定义对应的 interface
  public getPosts(): Observable<any> {
    return this.http.get(this.dataUrl);
  }
}
Copy after login

Next we modify app.component.ts and app.component.html

// app.component.ts
import { Component, OnInit } from &#39;@angular/core&#39;;
import { DataService } from &#39;./services/data.service&#39;;

@Component({
  selector: &#39;app-root&#39;,
  templateUrl: &#39;./app.component.html&#39;,
  styleUrls: [&#39;./app.component.scss&#39;]
})
export class AppComponent implements OnInit {
  title = &#39;pwa-demo&#39;;
  posts = [];

  constructor(private dataService: DataService) {}

  ngOnInit(): void {
    this.dataService.getPosts().subscribe((res) => {
      this.posts = res;
    });
  }
}
Copy after login
<div class="app">
  <h1>Hello PWA</h1>
  <br />
  {{ posts | json }}
</div>
Copy after login

So far if the project is normal After starting up, you should see the following page

Through a practical combat, lets see how PWA is applied to Angular projects

3 Disconnect from the Internet

After completing the preparations, let’s disconnect from the Internet and see what will happen. PressF12 Select NetWork and then select Offline.

Through a practical combat, lets see how PWA is applied to Angular projects

After refreshing, you will find that our page can no longer load normally

Through a practical combat, lets see how PWA is applied to Angular projects

4 PWA debut

Now it’s our turn for PWA.

First installpwa

ng add @angular/pwa
Copy after login

After the installation is complete, you will find that these files have changed

Through a practical combat, lets see how PWA is applied to Angular projects

Here We mainly focus on the ngsw-config.json file. The changes in other files are easy to understand. Everyone will know at a glance

Through a practical combat, lets see how PWA is applied to Angular projects

The files to be cached are defined in this file:

  • favicon.ico
  • index.html
  • manifest.webmanifest
  • JS and CSS bundles
  • All files under assets

Next we configure the requested interface into ngsw-config.json, more For configuration, please refer to Angular Service Worker Configuration

{
  ...,
  "dataGroups": [
    {
      "name": "api-posts",
      "urls": ["/posts"],
      "cacheConfig": {
        "maxSize": 100,
        "maxAge": "5d"
      }
    }
  ]
}
Copy after login

Rebuild our project after the configuration is completednpm run build:pwa

After the build is completed, pass npm run start:pwa to start our project. After successful startup, open http://127.0.0.1:8001 and you should be able to see

Through a practical combat, lets see how PWA is applied to Angular projects

We repeat the previous steps, disconnect the network and refresh again. You will find that the page can still be loaded normally.

Through a practical combat, lets see how PWA is applied to Angular projects

Let’s test our cache again and follow the steps below to try it

  1. Open an incognito browsing window first
  2. npm run start:pwa starts, and opens the page
  3. Close the tab (note that it is a tab, you cannot close the browser), turn off the http-server
  4. to app.component. Make some changes to html
  5. Rebuild and then start with http-server to open the page.

The result of the first startup

Through a practical combat, lets see how PWA is applied to Angular projects

Change app.component.html Chinese text is Hello PWA Demo, run againnpm run build:pwa && npm run start:pwa and then openhttp://127.0.0.1:8001 and you will find that the result has not changed

Through a practical combat, lets see how PWA is applied to Angular projects

At this time, if we refresh it again, we will find that the page has been refreshed to the one after our changes

1Through a practical combat, lets see how PWA is applied to Angular projects

5 Summary

For more related instructions, it is recommended that you refer to Angular official, and for related configurations, refer to Service Work Configuration. I hope this article can help everyone improve the performance and experience of front-end pages. Similarly, Angular also has a function App Shell, which is similar to the PWA we mentioned this time. Anyone who is interested can also check it out :).

DevUI: Experience makes the world a better place!

For more programming-related knowledge, please visit: Programming Teaching! !

The above is the detailed content of Through a practical combat, let's see how PWA is applied to Angular projects. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template