angular 漸進_如何創建具有Angular和無頭CMS的漸進式Web應用程序

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 installng 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使您的生活更輕松。 為此,請執行以下步驟:

  1. Set defaults.styleExt value from cssto scssin the/.angular-cli.jsonconfiguration file

    /.angular-cli.json配置文件中的defaults.styleExt值從css設置為scss

  2. Rename styles.css to styles.scss

    styles.css重命名為styles.scss

  3. Rename /src/app.component.css to /src/app.component.scssand reflect this renaming in app.component.ts in the component declaration atribute’s styleUrls 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&amp;hq=&amp;ll={{poi.latitude__decimal_degrees_.value}},{{poi.longitude__decimal_degrees_.value}}&amp;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.htmlfavicon.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 漸進

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/394206.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394206.shtml
英文地址,請注明出處:http://en.pswp.cn/news/394206.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

win10不用第三方工具激活的方法

步驟&#xff1a;1、本機上裝個win7旗艦版&#xff0c;這個得拿第三方工具激活一下&#xff0c;當然你如果已經購買了正版更沒問題了。第三方工具推薦那個啥啥loader&#xff0c;記住&#xff1a;chew_wga系列的暴力工具是不行的哦&#xff1b;2、把需要安裝的win10官方安裝鏡像…

CentOS 7 搭建 LAMP

一、安裝httpd 1、yum install httpd -y 2、啟動服務&#xff1a;systemctl start httpd 3、設置開機啟動&#xff1a;systemctl enable 二、安裝mariadb 1、yum groupinstall mariadb 2、啟動服務&#xff1a;systemctl start mariadb 3、設置開機啟動&#xff1a;systemctl e…

quartz教程二

轉載于:https://www.cnblogs.com/mumian2/p/10729901.html

python hookapi_pytest文檔70-Hook鉤子函數完整API總結?

pytest_collectstart(collector: Collector) 收集器開始收集。pytest_make_collect_report(collector: Collector) 執行collector.collect()并返回一個CollectReport。pytest_itemcollected(item: Item) 我們剛剛收集了一個測試項目。pytest_collectreport(report: Coll…

出現字跡模糊跡象_改變跡象:如何使用動態編程解決競爭性編程問題

出現字跡模糊跡象by Sachin Malhotra由Sachin Malhotra 改變跡象&#xff1a;如何使用動態編程解決競爭性編程問題 (Change the signs: how to use dynamic programming to solve a competitive programming question) If you’re a competitive programmer like I am, one of…

leetcode695. 島嶼的最大面積(dfs)

給定一個包含了一些 0 和 1 的非空二維數組 grid 。一個 島嶼 是由一些相鄰的 1 (代表土地) 構成的組合&#xff0c;這里的「相鄰」要求兩個 1 必須在水平或者豎直方向上相鄰。你可以假設 grid 的四個邊緣都被 0&#xff08;代表水&#xff09;包圍著。找到給定的二維數組中最大…

python把圖片轉為字符畫_Python 實現圖片轉換為字符畫

主要使用 pillow如果沒有安裝 使用 pillow install pillow 安裝一下看代碼&#xff1a;from PIL import Imageimport argparse#字符畫所用的字符集ascii_char list("$B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_~<>i!lI;:,\"^. ")def get…

冒泡的三種寫法

學而時習之&#xff0c;不亦說乎&#xff01; --《論語》 package com.zby.bubble;import java.util.Arrays; /*** * <class description>簡單初級冒泡算法java實現* author zby**/ public class PrimaryBubble {public static void main(String[] args) {int[] arr { 1…

76. Minimum Window Substring

最后更新 一刷 08-Jan-2017 昨天Amazon group面結束&#xff0c;剛回家。 國內以前喜歡的女生結婚了&#xff0c;嘿嘿...好開心呀~~ 這次面試感覺自己的做法完爆別人&#xff0c;比什么2 greedy好多了 總之表現比想象的好&#xff0c;最后一面的面試官真是聰明得一逼&#xff…

day 02 python 基礎

1.day1作業講解 題目答案見day1 2.格式化輸出 %占位符&#xff0c;s:字符串&#xff0c;d&#xff1a;數字 %%只是單純的顯示%&#xff08;顯示的%是后面的&#xff09; 1 #格式化輸出2 # % s d3 # name input(請輸入姓名)4 # age input(請輸入年齡)5 # height input(請輸入…

python多維數據劃分_【python+機器學習(4)】多維數據的特征選取(RidgeLasso)...

歡迎關注哈希大數據微信公眾號【哈希大數據】在之前我們介紹了直接使用線性回歸進行波士頓房價的預測&#xff0c;但是預測準確率僅有60%左右。預測準確率不高一方面是我們未對數據進行一定的預處理(包括歸一化和標準化等)&#xff0c;這樣不能確保在使用優化方式時&#xff0c…

leetcode64. 最小路徑和(dp)

給定一個包含非負整數的 m x n 網格&#xff0c;請找出一條從左上角到右下角的路徑&#xff0c;使得路徑上的數字總和為最小。說明&#xff1a;每次只能向下或者向右移動一步。示例:輸入: [[1,3,1],[1,5,1],[4,2,1] ] 輸出: 7 解釋: 因為路徑 1→3→1→1→1 的總和最小。代碼 …

mysql淺拷貝_深拷貝與淺拷貝

在Python中&#xff0c;對象賦值實際上是對象的引用。當創建一個對象&#xff0c;然后把它賦給另一個變量的時候&#xff0c;Python并沒有拷貝這個對象&#xff0c;而只是拷貝了這個對象的引用。1、淺拷貝&#xff1a;利用切片操作、工廠方法list方法拷貝2、深拷貝&#xff1a;…

盤州市“檢企聯合” 探索大數據應用新路

為認真貫徹落實“科技強檢”及推進大數據應用的決策部署&#xff0c;8月31日&#xff0c;盤州市人民檢察院組織召開以“檢察大數據”為主題的“兩長”座談會。市經信局、中國移動盤州分公司、中國電信盤州分公司等單位負責人&#xff0c;檢察院在家班子成員及院各部門主要負責人…

iOS中的顏色

最近在改Bug的時候&#xff0c;才注意到iOS 中的顏色竟然也大有文章&#xff0c;特來記錄一下。 先說一下問題&#xff0c;因為某界面中有用xib實現的一個view&#xff0c;而這個view 只在UIColletionView的layout 里通過nib 注冊使用&#xff0c;為這個xib設置了背景色&#x…

編程面試中需要了解的5件事

This article is intended for those who are trying to start their programming career, or are preparing to interview for their dream job. As someone who’s been on both sides of the interviewing table, I understand how it feels to be the interviewee.本文適用…

多線程的基礎知識

1、程序、進程、線程的基本概念 程序&#xff1a;為了完成某種任務用某一種語言編寫的一組指令的集合就叫程序。程序就是一段靜態的代碼。 進程&#xff1a;進程是程序的依次執行過程&#xff0c;或者說是正在運行的一個程序。這是一個動態的過程&#xff0c;有它自身的產生運行…

springboot實現單點登錄_什么是單點登錄,php是如何實現單點登錄的

文章來自&#xff1a;php中文網鏈接&#xff1a;https://www.php.cn/php-weizijiaocheng-429869.html作者&#xff1a;中文網商務合作:請加微信(QQ)&#xff1a;2230304070視頻教程分享碼農網&#xff1a;http://www.mano100.cn/rjyfk_url-url.html &#xff0c;升級終身會員即…

背景圖處理,這是個好東西記錄一下

背景圖處理 rgba &#xff08;&#xff09;&#xff0c;前3個是三原色&#xff0c;第四個參數是透明度轉載于:https://www.cnblogs.com/ChineseLiao/p/7479207.html

python使用GUI(圖形用戶界面)

打開后&#xff1a; File→New File(Ctrl N) 轉載于:https://www.cnblogs.com/ly123456/p/6269859.html