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.mzph.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