angular 漸進
by Ondrej Chrastina
通過Ondrej Chrastina
如何創建具有Angular和無頭CMS的漸進式Web應用程序 (How to create a progressive web app featuring Angular and headless CMS)
Have you ever wondered how a headless Content Management System fits in with Progressive Web Apps?
您是否想過無頭內容管理系統如何與Progressive Web Apps配合使用?
I recently read my colleague Bryan’s story about Progressive Web Apps. The article talks about the implementation of a Progressive Web App (PWA) that lists interesting places stored in the headless CMS.
我最近閱讀了同事Bryan關于Progressive Web Apps的故事 。 本文討論了漸進式Web應用程序 (PWA)的實現,該應用程序列出了存儲在無頭CMS中的有趣位置。
You could install this app on your device. It uses a service worker to cache the application and data about the points of interest. The application was written in plain JavaScript.
您可以在設備上安裝此應用。 它使用服務工作者來緩存應用程序和有關興趣點的數據。 該應用程序是用純JavaScript編寫的。
Having written a good share of JavaScript code, I wanted to expand on the concept using more complex frameworks.
在編寫了大量JavaScript代碼之后,我想使用更復雜的框架擴展這個概念。
I narrowed my choices down to three big players — React, Vue, and Angular. I chose to use Angular, because it has already support for service workers, and I wanted to use TypeScript.
我將選擇范圍縮小到三個大公司-React,Vue和Angular。 我選擇使用Angular,因為它已經支持服務人員,并且我想使用TypeScript 。
Each step of this tutorial will be accompanied by a link to a GitHub commit. This way, you’ll always be able to see what the code looks like.
本教程的每個步驟都將帶有指向GitHub提交的鏈接。 這樣,您將始終能夠看到代碼的外觀。
To run the app, just download or clone the commit and run npm install
and ng serve -o
. The whole code is stored in one of the branches.
要運行該應用程序,只需下載或克隆提交,然后運行npm install
和ng serve -o
。 整個代碼存儲在分支之一中 。
Let’s get to it!
讓我們開始吧!
先決條件 (Prerequisites)
node.js v8+
node.js v8 +
Angular CLI v.1.7.4 installed as a global dependency via the npm package manager:
npm install -g @angular/cli
通過npm軟件包管理器將Angular CLI v.1.7.4安裝為全局依賴項:
npm install -g @angular/cli
入門 (Getting started)
First of all, generate a new project. You can easily generate all boilerplate code using the awesome Angular CLI tools. Just navigate to a folder and generate a ready-to-run code:
首先,生成一個新項目。 您可以使用強大的Angular CLI工具輕松生成所有樣板代碼。 只需導航到一個文件夾并生成一個現成的代碼即可:
ng new cloud-sample-angular-pwa-aps
樣板配置 (Boilerplate configuration)
There are a few steps to configure the boilerplate.
有幾個步驟可配置樣板。
The generated code uses plain CSS by default. But, you might want to make your life easier with SCSS. To achieve this, perform these steps:
默認情況下,生成的代碼使用普通CSS。 但是,您可能希望使用SCSS使您的生活更輕松。 為此,請執行以下步驟:
Set
defaults.styleExt
value fromcss
toscss
in the/.angular-cli.json
configuration file將
/.angular-cli.json
配置文件中的defaults.styleExt
值從css
設置為scss
Rename
styles.css
tostyles.scss
將
styles.css
重命名為styles.scss
Rename
/src/app.component.css
to/src/app.component.scss
and reflect this renaming inapp.component.ts
in the component declaration atribute’sstyleUrls
property value.將
/src/app.component.css
重命名為/src/app.component.scss
并在app.component.ts
中的組件聲明屬性的styleUrls
屬性值中反映此重命名。
為應用 創建一些初始內容 (Create some initial content for the app)
Global styles: /src/styles.scss
全局樣式: /src/styles.scss
Component: /src/app/app.component.html and /src/app/app.component.scss
組件: /src/app/app.component.html和/src/app/app.component.scss
Lets have a look!
我們來看一下!
Just run this command:
只需運行以下命令:
ng serve -o
加載數據 (Load the data)
Let’s finally use the power of Angular. In this section, we will define an injectable client that allows the app to get Kentico Cloud data. I will use the same data source as Bryan used in his article.
最后,讓我們使用Angular的功能。 在本節中,我們將定義一個允許應用程序獲取Kentico Cloud數據的可注入客戶端。 我將使用Bryan在他的文章中使用的相同數據源。
First of all, install Kentico Cloud Delivery SDK via the following command:
首先,通過以下命令安裝Kentico Cloud Delivery SDK :
npm install -P kentico-cloud-delivery-typescript-sdk
Then, create a client provider that will be used in dependency injection.
然后,創建將在依賴項注入中使用的客戶端提供程序。
Create a new file in the /src/app
folder and name it delivery-client.provider.ts
. This provider module needs to export an object defining the factory used to create our client. In the code below, you can see the ID of the project in Kentico Cloud where the data is stored.
在/src/app
文件夾中創建一個新文件,并將其命名為delivery-client.provider.ts
。 此提供程序模塊需要導出一個對象,該對象定義用于創建客戶端的工廠。 在下面的代碼中,您可以在存儲數據的Kentico Cloud中查看項目的ID。
import { DeliveryClient, DeliveryClientConfig } from 'kentico-cloud-delivery-typescript-sdk';export const DeliveryClientFactory = (): DeliveryClient => {const projectId = '975bf280-fd91-488c-994c-2f04416e5ee3';return new DeliveryClient(new DeliveryClientConfig(projectId, []));
};export const DeliveryClientProvider = {provide: DeliveryClient,useFactory: DeliveryClientFactory,deps: []
};
Next, edit app.module.ts
. This is the place where you state which modules are loaded.
接下來,編輯app.module.ts
。 這是您說明要加載哪些模塊的地方。
...
import { DeliveryClientProvider } from './delivery-client.provider';
...@NgModule({
...
providers: [DeliveryClientProvider]
...
})
Now we are ready to use the client in the app component.
現在,我們準備在應用程序組件中使用客戶端。
We will set up the app.component.ts
to use the DeliverClient
that is auto-magically injected as a parameter to the constructor. We’ll also subscribe the component to the client’s observable and we’ll define a corresponding observer action.
我們將設置app.component.ts
以使用自動傳遞為構造函數參數的DeliverClient
。 我們還將使該組件訂閱客戶端的可觀察對象,并定義相應的觀察者動作。
import { Component, OnInit, OnDestroy } from '@angular/core';
import { DeliveryClient, ContentItem } from 'kentico-cloud-delivery-typescript-sdk';
import { Subscription } from 'rxjs/Subscription';@Component({selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.scss']
})export class AppComponent implements OnInit, OnDestroy {dataSubscription: Subscription;pointsOfInterest: ContentItem[];constructor(private deliveryClient: DeliveryClient) { }ngOnInit() {this.dataSubscription = this.deliveryClient.items<ContentItem>().type('point_of_interest').get().subscribe(response => {this.pointsOfInterest = response.items;});}ngOnDestroy(): void {this.dataSubscription.unsubscribe();}
}
The last step is to display the data from CMS using the Angular ngFor
directive to iterate through the items and render them.
最后一步是使用Angular ngFor
指令顯示來自CMS的數據,以遍歷項目并進行渲染。
<header><h2>Pack and Go</h2>
</header>
<main class="main"><div class="card" *ngFor="let poi of pointsOfInterest"><h2 class="title">{{poi.title.value}}</h2><div class="content" innerHTML="{{poi.description.value}}"></div><a class="map-link" target="_blank" href="http://maps.google.com/?ie=UTF8&hq=&ll={{poi.latitude__decimal_degrees_.value}},{{poi.longitude__decimal_degrees_.value}}&z=16">Open the map</a></div>
</main>
允許添加快捷方式圖標 (Allow adding a shortcut icon)
Now, we’ll make the app capable of adding its icon to the desktop or start screen of the device.
現在,我們將使該應用程序能夠將其圖標添加到設備的桌面或開始屏幕。
This step is quite easy. It requires us to create a JSON file containing metadata about the app and link it from the head
tag. The manifest file should point to multiple URLs of icons in various sizes.
這一步很容易。 它要求我們創建一個包含有關該應用程序的元數據的JSON文件,并從head
標簽進行鏈接。 清單文件應指向各種大小的圖標的多個URL。
We should also list the manifest.json
file in an assets declaration in the .angular-cli.json
configuration file.
我們還應該列出manifest.json
中在財產申報文件.angular-cli.json
配置文件。
{...apps: {assets : [...,"manifest.json"],...},...
}
But, more importantly, link to the manifest.json
file from index.html
.
但是,更重要的是,可以從index.html
鏈接到manifest.json
文件。
<link rel="manifest" href="manifest.json" />
Finally, we’ll create the manifest itself, together with all the icon renditions. Take a look at the link below to see the result.
最后,我們將創建清單本身以及所有圖標格式。 查看下面的鏈接以查看結果。
設置服務人員 (Set up the service worker)
The concept of the service worker is what makes PWA apps revolutionary.
服務工作者的概念使PWA應用程序具有革命性。
Service workers work as a proxy between the client and the internet. Depending on the actual configuration, the service worker can pre-cache the app skeleton (called the ‘app shell’) during the first load. This means that subsequent requests are blazing-fast. The service worker can also silently cache all other application data.
服務人員充當客戶端和Internet之間的代理。 根據實際配置,服務工作者可以在首次加載期間預先緩存應用程序框架(稱為“應用程序外殼”)。 這意味著隨后的請求很快。 服務工作者還可以靜默緩存所有其他應用程序數據。
First of all, it is required to install the service worker module to the application.
首先,需要將Service Worker模塊安裝到應用程序。
npm install -P @angular/service-worker
Now enable the service worker in Angular in the .angular-cli.json
configuration file.
現在,在.angular-cli.json
配置文件中在Angular中啟用服務工作者。
{...apps: {"serviceWorker": true,...},...
}
Now, let’s import the service worker module to our app using the app.module.ts
file.
現在,讓我們使用app.module.ts
文件將服務工作者模塊導入到我們的應用程序中。
...
import { ServiceWorkerModule } from '@angular/service-worker';
...
@NgModule({...imports: [...ServiceWorkerModule.register('/ngsw-worker.js', { enabled: environment.production })],...
})
?...
The last thing is to configure the caching strategies for the app shell and the data. First we need to create ngsw-config.json
configuration file under the /src
folder.
最后一件事是為應用程序外殼程序和數據配置緩存策略。 首先,我們需要在/src
文件夾下創建ngsw-config.json
配置文件。
For the app shell, we’ll use the default set up described in the documentation. This configuration will pre-fetch index.html
, the favicon.ico
, and the app shell, including the linked CSS and JavaScript bundles. Files in /assets
folder are lazy-loaded.
對于應用程序外殼,我們將使用文檔中描述的默認設置。 此配置將預取index.html
, favicon.ico
和應用程序外殼,包括鏈接CSS和JavaScript捆綁包。 /assets
文件夾中的文件是延遲加載的。
Requests for the data from Kentico Cloud will use another caching strategy. We will define an API endpoint as a new data group and set the caching to use the freshness strategy. In the commit link bellow, you can see the whole content of the configuration file.
來自Kentico Cloud的數據請求將使用另一種緩存策略。 我們將API端點定義為新的數據組,并設置緩存以使用新鮮度策略。 在下面的提交鏈接中,您可以看到配置文件的全部內容。
Now we are ready to install the app on the device. For instance, in Chrome in Android, you can do so by tapping the ellipsis glyph and choosing “Add to Home screen”.
現在,我們準備在設備上安裝該應用程序。 例如,在Android的Chrome中,您可以通過點擊省略號字形并選擇“添加到主屏幕”來實現。
All right, we’re done. Despite a quick and simple implementation, the app is quite powerful and fast. And we’re free to extend it in various ways, like importing the material design or font icons.
好吧,我們完成了。 盡管實現過程簡單快捷,但該應用程序功能強大且快速。 而且我們可以自由地以各種方式擴展它,例如導入材質設計或字體圖標。
The PWA APIs also allow us to use cool native features such as:
PWA API還允許我們使用很酷的本機功能,例如:
- read device’s sensors 讀取設備的傳感器
- display push notifications 顯示推送通知
- and use the device’s cameras. 并使用設備的相機。
Our app could also sense when the device transitions from online to offline, and vice versa. We could also use the automatically generated, strongly-typed models of content items from the CMS.
我們的應用還可以感應設備何時 從在線過渡到離線,反之亦然。 我們還可以使用由CMS 自動生成的內容類型強類型模型 。
As you can see, creating a PWA in Angular is easy, yet allows us to extend the app much further.
如您所見,在Angular中創建PWA很容易,但是允許我們進一步擴展應用程序。
翻譯自: https://www.freecodecamp.org/news/how-to-create-a-progressive-web-app-featuring-angular-and-headless-cms-b8ee4f7a5ea3/
angular 漸進