In Angular, service is a module where data fetching and implement CMS integration and later inject the service in components and modules.
Contentful
Contentful is headless CMS, a service like Word Press, can used to create backend for content oriented web/mobile app.
For integrating contentful CMS with Angular, first we need a service to inject data to components, also require the contentful package
Create a new Angular project, and add the dependency
ng new myproject
yarn add contenful
let’s add a service
ng g s contentfulservice
this will add a service to your project
add a client and fetchPost method in the service
import { createClient,Entry } from 'contentful';
import { Injectable } from '@angular/core';
import {from, Observable} from 'rxjs';
import { environment } from '../environments/environment';
@Injectable({
providedIn: 'root'
})
export class BlogAPIService {
private clinet = createClient(environment.config);
constructor( ) { }
fetchPosts() {
const promise=this.clinet.getEntries();
return from(promise);
}
}
In the above we converted the promise to observable using from .
Also need to configure the environment file configure the contentful credentials which can be obtained from contentful setting (API)
export const environment = {
production: false,
config: {
space:'w591jyzdi2py',
accessToken:'DXG7DohnxRncpcxSPtLGr5fR4_fzjyzRzVZAiP9Ussk'
}
};
Inject the service
In any component , inject the service using the constructor as follows
Here is home component example.
import {Component, OnInit} from '@angular/core';
import {BlogAPIService} from '../blog-api.service';
import {Observable} from "rxjs";
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
entries$:Observable<any> | undefined;
constructor(private blogService:ContenfulService) {
}
ngOnInit(): void {
this.entries$=this.blogService.fetchPosts();
}
}
In the template we can convert the observable and render using *ngif
<main *ngIf="entries$ | async as entries">
{{entries | json}}
</main>