angular 渐进_如何创建具有Angular和无头CMS的渐进式Web应用程序

赵永逸
2023-12-01

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)

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 渐进

 类似资料: