Este tutorial es una continuación de mi tutorial anterior sobre cómo crear una aplicación Vue.js con CMS sin servidor y le muestra cómo crear una aplicación Angular con CMS sin servidor.

Angular, desarrollado y mantenido por ingenieros de Google, ha encontrado un lugar en las aplicaciones web dinámicas y es un lenguaje cada vez más solicitado. Es un lenguaje robusto y completo para el desarrollo front-end que está listo para pruebas unitarias, lo que lo convierte en el lenguaje elegido por muchos desarrolladores. Angular simplifica la experiencia de desarrollo de front-end al extender la sintaxis de HTML para permitirle crear rápidamente la capacidad de administración de contenido.
Debido a la simplicidad de Angular, los desarrolladores la aprovechan cada vez más para agregar capacidad CMS a los sitios web.
Para los usuarios de Wordpress, una forma popular de integrar la capacidad de gestión de contenido es trabajar con la biblioteca wp-api-angular que le permite interactuar con la API de Wordpress y las aplicaciones angulares. Si está utilizando Wordpress como plataforma CMS, el uso de Angular y la API de Wordpress puede reducir los tiempos de carga del contenido de su página.
Para aquellos que no usan Wordpress, hay una nueva generación de CMS basados en API que simplifican enormemente las cosas. Discutiremos un ejemplo aquí.
En este artículo, usaremos ButterCMS como una alternativa a Wordpress y un ejemplo de un CMS sin cabeza basado en SaaS que proporciona un panel de control de CMS alojado y una API de contenido que puede consultar desde su aplicación Angular. Esto significa que no necesita poner en marcha ninguna nueva infraestructura para agregar CMS a su aplicación Angular.
Este tutorial demostrará cómo construir una aplicación Angular impulsada por CMS que tiene páginas de marketing (estudios de casos de clientes), un blog y preguntas frecuentes, todo impulsado a través de API. ¡No se necesitan servidores!
Instalación
Primero, comenzará instalando el Angular cli.
npm install -g @angular/cli
Configure un nuevo proyecto Angular usando Angular cli. De forma predeterminada, angular-cli usa el estilo CSS, por lo que agregar la —-style=scss
bandera le indica a Angular CLI que use SCSS en su lugar.
ng new hello-buttercms-project --style=scsscd hello-buttercms-project
Instale los paquetes relacionados con Angular Material y Angular Material.
npm install --save @angular/material @angular/cdknpm install --save @angular/animations
Instale ButterCMS. Ejecute esto en su línea de comando:
npm install buttercms --save
La mantequilla también se puede cargar usando un CDN:
Empiece rápidamente
Abra el proyecto en el editor de código que elija. En src / app, crea un directorio llamado_services
Crearemos un archivo llamado butterCMS.service.js
. Esto le permite tener su API Token en un solo lugar y no alterarlo accidentalmente.
import * as Butter from 'buttercms';
export const butterService = Butter('b60a008584313ed21803780bc9208557b3b49fbb');
Importará este archivo a cualquier componente en el que desee utilizar ButterCMS.
Para una guía de inicio rápido, vaya a src/app/hello-you/hello-you.component.ts
e importebutterService
import {butterService} from '../_services';
Dentro de HelloYouComponent
, cree métodos:
fetchPosts() { butter.post.list({ page: 1, page_size: 10 }) .then((res) => { console.log(‘Content from ButterCMS’) console.log(res) })}
Ahora llame a este método cuando el componente esté cargado agregándolo al OnInit
gancho del ciclo de vida:
ngOnInit() { this.fetchPosts();}
Esta solicitud de API obtiene una publicación de blog de muestra. Su cuenta viene con una publicación de ejemplo que verá en la respuesta. Si recibe una respuesta, significa que ahora puede conectarse a la API.
Agregar páginas de marketing
La configuración de páginas impulsadas por CMS es un proceso de tres pasos:
- Definir el tipo de página
- Crear una pagina
- Integre en su aplicación
Definir página
Primero, cree un tipo de página para representar las páginas de su estudio de caso de cliente. A continuación, defina los campos que desee para los estudios de casos de sus clientes. Con su tipo de página definido, ahora puede crear la primera página de estudio de caso. Especifique el nombre y la URL de la página y luego complete el contenido de la página.

Con su página definida, la API ButterCMS la devolverá en formato JSON como este:
{ "data": { "slug": "acme-co", "fields": { "facebook_open_graph_title": "Acme Co loves ButterCMS", "seo_title": "Acme Co Customer Case Study", "headline": "Acme Co saved 200% on Anvil costs with ButterCMS", "testimonial": "We’ve been able to make anvils faster than ever before! — Chief Anvil Maker
\r\n", "customer_logo": "//cdn.buttercms.com/c8oSTGcwQDC5I58km5WV", } } }
Esta guía utiliza el marco Angular y Angular CLI para generar todos los componentes y empaquetar nuestra aplicación.
Vayamos al código.
Crear nuevo proyecto
ng new buttercms-project --style=scsscd buttercms-projectnpm install --save @angular/material @angular/cdknpm install --save @angular/animationsnpm install -S buttercmsng serve
Su localhost: 4200 debería estar listo para servir su página Angular.
Crear mecanografiado para exportar el servicio ButterCMS
Debajo src/app
cree un directorio llamado _services
. Cree un archivo llamado butterCMS.service.js
.
import * as Butter from 'buttercms';export const butterService = Butter('your_api_token');
Actualizar las rutas de los componentes
Estos componentes son generados por Angular CLI usando:
ng g component
Under
src/app
create a file called app-routing.module.ts
import {NgModule} from '@angular/core';import {RouterModule, Routes} from '@angular/router';import {CustomerComponent} from './customer/listing/customer.listing.component';import {FaqComponent} from './faq/faq.component';import {BlogPostComponent} from './blog-post/listing/blog-post.component';import {HomeComponent} from './home/home.component';import {CustomerDetailsComponent} from './customer/details/customer.details.component';import {BlogPostDetailsComponent} from './blog-post/details/blog-post.details.component';import {FeedComponent} from './feed/feed.component';import {HelloYouComponent} from './hello-you/hello-you.component';
const appRoutes: Routes = [ {path: 'customer', component: CustomerComponent}, {path: 'customer/:slug', component: CustomerDetailsComponent}, {path: 'faq', component: FaqComponent}, {path: 'blog', component: BlogPostComponent}, {path: 'blog/:slug', component: BlogPostDetailsComponent}, {path: 'rss', component: FeedComponent}, {path: 'hello-you', component: HelloYouComponent}, {path: 'home', component: HomeComponent}, {path: '**', redirectTo: 'home'}];
@NgModule({ imports: [RouterModule.forRoot(appRoutes)], exports: [RouterModule]})export class AppRoutingModule {}
Set up the Customer List page
Under
apps/customer
type: ng g component
In the file
apps/customer/listing/customer.listing.component.ts
:
Import
butterService
In
OnInit
hook, usebutterService
to get the list of customersStore results in pages variable and markup (HTML) will be updated with the data
import {Component, OnInit} from '@angular/core';import {butterService} from '../../_services';
@Component({ selector: 'app-customer', templateUrl: './customer.listing.component.html', styleUrls: ['./customer.listing.component.scss']})
export class CustomerComponent implements OnInit { public pages: any[]; constructor() { }
ngOnInit() { butterService.page.list(‘customer_case_study’) .then((res) => { this.pages = res.data.data; }); }}
Display the results in
customer.listing.component.html
;Customers
whatshot
Configurar la página de detalles del cliente
Under apps/customer
, type ng g component details
.
apps/customer/details/customer.details.component.ts
Create customer page
- Import
butterService
- In
OnInit
hook, usebutterService
to get the customer page given the slug in the URL path - Store results in page variable and markup (HTML) will be updated with the customer data
import {Component, OnInit} from '@angular/core';import {Observable} from 'rxjs/Observable';import {ActivatedRoute} from '@angular/router';import {butterService} from '../../_services';import {map, take} from 'rxjs/operators';
@Component({ selector: 'app-customer-details', templateUrl: './customer.details.component.html', styleUrls: ['./customer.details.component.scss']})
export class CustomerDetailsComponent implements OnInit { constructor(protected route: ActivatedRoute) { }
protected slug$: Observable; public page: any;
ngOnInit() { this.slug$ = this.route.paramMap .pipe( map(params => (params.get('slug'))) );
this.slug$.pipe( take(1)) .subscribe(slug => { butterService.page.retrieve('customer_case_study', slug) .then((res) => { this.page = res.data.data; }).catch((res) => { console.log(res); }); }); } }
Display the results in customer.details.component.html
{{page.fields.headline}}
Testimonials
You can now navigate to the Customer Page via the list of all Customer Pages or directly via URL.
Add a knowledge base
Set up content fields
Let’s suppose you want to add a CMS to a static FAQ page with a title and a list of questions with answers.
Making your content dynamic with Butter is a two-step process:
- Setup custom content fields in Butter
- Integrate the fields into your application
To setup custom content fields, first sign in to the Butter dashboard.
Create a new workspace or click on an existing one. Workspaces let you organize content fields in a friendly way for content editors and have no effect on development or the API. For example, a real-estate website might have a workspace called “Properties” and another called “About Page”.

Once you’re in a workspace click the button to create a new content field. Choose the “Object” type and name the field “FAQ Headline.”

After saving, add another field, but this time choose the “Collection” type and name the field FAQ Items
.
On the next screen, setup two properties for items in the collection.
Now go back to your workspace and update your heading and FAQ items.
Integrate your app
Create FAQ Component
Under apps
type: ng g component faq
apps/faq/faq.component.ts
Set up onInit hook to load FAQ
import {Component, OnInit} from '@angular/core';import {butterService} from '../_services';
@Component({ selector: 'app-faq', templateUrl: './faq.component.html', styleUrls: ['./faq.component.scss']})
export class FaqComponent implements OnInit { constructor() {}
public faq: any = { items: [], title: 'FAQ' };
ngOnInit() { butterService.content.retrieve(['faq_headline', 'faq_items']) .then((res) => { console.log(res.data.data); this.faq.title = res.data.data.faq_headline; this.faq.items = res.data.data.faq_items; }); }}
Display the result
; {{item.question}}
The values entered in the Butter dashboard will immediately update the content in our app.
Blogging
To display posts, you need to create a
/blog
route in your app and fetch blog posts from the Butter API, as well as a /blog/:slug
route to handle individual posts.
See the API reference for additional options such as filtering by category or author. The response also includes some metadata we’ll use for pagination.
Set up Blog Homepage
Under
apps/blog-post
, type: ng g component listing
.
apps/blog-post/listing/blog-post.listing.component.ts
Update component to get all posts:
Import
butterService
Get all post
onInit
import {Component, OnInit} from '@angular/core';import {butterService} from '../../_services';
@Component({ selector: 'app-blog-post', templateUrl: './blog-post.component.html', styleUrls: ['./blog-post.component.scss']})export class BlogPostComponent implements OnInit { public posts: any[];
constructor() { }
ngOnInit() { butterService.post.list({ page: 1, page_size: 10}).then((res) => { console.log(res.data) this.posts = res.data.data; }); }}
Display the result:
Blog Posts;
;
;
whatshot
Set up Blog Post page
Under apps/blog-post
, type: ng g component details
apps/blog-post/details/blog-post.details.component.ts
- Import
butterService
- In
OnInit
hook, usebutterService
to get the blog-post post given the slug in the URL path - Store results in post variable and markup (HTML) will be updated with the customer data
import {Component, OnInit, ViewEncapsulation} from '@angular/core';import {Observable} from 'rxjs/Observable';import {ActivatedRoute} from '@angular/router';import {butterService} from '../../_services';import {map, take} from 'rxjs/operators';
@Component({ selector: 'app-blog-post-details', templateUrl: './blog-post.details.component.html', styleUrls: ['./blog-post.details.component.scss'], encapsulation: ViewEncapsulation.None})
export class BlogPostDetailsComponent implements OnInit {
constructor(protected route: ActivatedRoute) { }
protected slug$: Observable; public post = { meta: null, data: null};
ngOnInit() { this.slug$ = this.route.paramMap .pipe( map(params => (params.get('slug'))) );
this.slug$.pipe( take(1)) .subscribe(slug => { butterService.post.retrieve(slug) .then((res) => { this.post = res.data; }).catch((res) => { console.log(res); }); }); }}
{{post.data.title}} < ;> ; {{post.data.author.first_name}} {{post.data.author.last_name}}
Now your app has a working blog that can be updated easily in the ButterCMS dashboard.
Categories, tags, and authors
Use Butter’s APIs for categories, tags, and authors to feature and filter content on your blog.
List all categories and get posts by category
Call these methods on the onInit()
lifecycle hook:
methods: { ... getCategories() { butter.category.list() .then((res) => { console.log('List of Categories:') console.log(res.data.data) }) }, getPostsByCategory() { butter.category.retrieve('example-category', { include: 'recent_posts' }) .then((res) => { console.log('Posts with specific category:') console.log(res) }) } }, created() { ... this.getCategories() this.getPostsByCategory()}
getCategories() { butter.category.list() .then((res) => { console.log(‘List of Categories:’) console.log(res.data.data) }) }, getPostsByCategory() { butter.category.retrieve(‘example-category’, { include: ‘recent_posts’ }) .then((res) => { console.log(‘Posts with specific category:’) console.log(res) }) }},created() { … this.getCategories() this.getPostsByCategory()}