Contentful service in Angular

Create contentful service and integrate contents with Angular.


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>

Editor frameworks for JS apps

About Javascript Editor frameworks


If you are building content based application such as blog, may want featured editor, such as Post editor or comment box. Making such an editor with all formatting capabilities would be tiresome.

Editor frameworks and wrapper libraries help us achieve this goal with ease and peace. I don’t intended to review each of these , instead I would to list best of them and in the up coming posts we will learn using these awesome editor frameworks.

My Picks

I like block editor mostly for content management, in my react app I will choose the Editor.js . It is easy to configure and use.

Second most useful framework for content management is Drftjs , which is maintained by Facebook itself. It is a complete Editor framework featuring mention, hashtag etc and it’s flexible too.

Here is complete list of framework available for building a full featured editor in your next JS / React/Vue/Angular app

Prisma MongoDB connection

How to configure MongoDB (local and Cloud based ) in Prisma ORM


Prisma is a Typescript based ORM for Javascript Frameworks such as React, Vuejs and Angular. It allows developers easily configure database and hand data using model classes.

Mongo DB

MongoDB is a NoSQL database for web, primarily. It is widely used in cloud based web and Mobile application.

How to configure MongoDB on Prima

In Prisma configuration file we can use preview version on MongoDB driver. The connection string can be stored in .env file (at the route of your project).

Local database

Form local database we can use the following connection string

//.env
 DATABASE_URL = mongodb://localhost:27017/blogdata?retryWrites=true&w=majority

Mongo Atlas database

For cloud based Mongo database we have to rely on the following connection.

//.env
 DATABASE_URL = mongodb+srv://admin:RRHEfMsK8zHWsGTI@cluster0.cqnll.mongodb.net/myFirstDatabase?retryWrites=true&w=majority

schema.prisma

Finally the Prisma Schema file would look like the following,

datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}

generator client {
  provider        = "prisma-client-js"
  previewFeatures = ["mongodb"]
}

model User {

  id    String @id @default(auto()) @map("_id") @db.ObjectId

  email String

} 

Migrating DB

If you are familiar with Prisma and Schema, we used to run migrate command to update the database with model.

There is an exception for Mongo, you don’t need to Migrate, instead run npx prisma generate command after any change made to schema.

To update the model we use npx prisma db push command.

Single Page app, what it really means ?

What is SPA and what does meant ti you.


From time to time we have been hearing this single page notion. Is it mean you can have only single html page ? Why should I creating a single page app ? Waste of time ?

Single Page App

With the emergence of front end frameworks such as React, Angular and Vue the notion SPA in use. As the name indicate it works as single page, but in reality, it can be works as other web pages does.

One word about front end library, the function of a front-end library is to display content from server, in other words they works in client side, but there are few exceptions.

SPA that work as Multiple page

Generally a web app/ website consisting of multiple page could have , a home , product, contact, about pages. A web app using Vue/React by default can have a single page, index page.

How how can I add more pages ? Here the router come into light. Router are links to components. We can create web page as component and place them into our index.html file.

When the user click the router link, it switches the component and hence work like other websites, make sense ?

Wanna start learning Vue/React ?

What should I know , this will be the first question and what type of computer should I have ?

  • HTML,CSS
  • JAVASCRIPT
  • A average laptop/desktop
  • Internet Connection
  • VS Code for debugging and editing.

Following Vue posts may help you get started

How to capture data in Angular ReactiveForm using Form Builder

How to capture data from a Angular reactive form using formbuilder


Form submission is an essential part of any commercial application. So lets learn about capturing data in Reactive Form which is give emphasize to component side.

We can use advance form builder to create model, interact with form data, validation ect.

  • Import Form Builder
  • Add dependency injection in constructor
  • Create a group using Form Builder service
  • Create getters for easy access
  • Bind the fomGroup and FormControlName

app.module import

We have to add import ReactiveFormsModule to app.module.ts as follows

import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
.....
 imports: [
    BrowserModule,
    ReactiveFormsModule,   
  ],

Form Builder in component.ts

Form Builder service allows to create formGroup with various property like validation. Also declared three getter functions to quickly access data. The code of our component class will look like

import {FormBuilder } from '@angular/forms';
... 
 constructor(private fb: FormBuilder) {}   
  get Item(): any {
    return this.todoForm.get("item");
  }
  get Desc(): any {
    return this.todoForm.get("description");
  }
todoForm = this.fb.group({
    item: ["formBuilder example", [Validators.required, Validators.minLength(4)]],
    description: ["", Validators.required],
  });

Binding the control

We can replace the name property of input with formControlName. So that the data in the FormGroup will be automatically updated. and the template will look like

{{todoForm | json}}
<form [formGroup]="todoForm"   novalidation (ngSubmit)="OnSubmit()"  >
      <div class="form-group">
      <label>Title</label>
 <input type="text" required  [class.is-invalid]="Item.invalid && Item.touched" class="form-control" formControlName="item">
      </div>
      <div class="form-group ">
      <label>Description</label>
      <textarea class="form-control" formControlName="description" ></textarea>
      </div>
       <button  type="submit" class="btn btn-primary">Submit</button>
      </form>

The interpolation statement will display the data.

When ever the user change the data the {{todoForm | json}} will output the value and it is live data.

Now you know how to capture data in a Reactive form using formBuilder

A set form projects available in the Source-Code Page

These angular post may help you

[display posts tag=angular-form]

How to capture data in Angular ReactiveForm using FormGroup

How to capture data from a Angular reactive form using formGroup


Form submission is an essential part of any commercial application. So lets learn about capturing data in Reactive Form which is give emphasize to component side.

app.module import

We have to import ReactiveFormsModule to app.module.ts as follows

import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
.....
 imports: [
    BrowserModule,
    ReactiveFormsModule,   
  ],

The following is required to capture data using FormGroup and Formcontrol.

  • Create a FormGroup
  • Bind the formGroup
  • Assigning formControlName

Create FormGroup and Bind it with Form

By using a Form Group we are creating alternative to Model class. The Group can be linked to a <form> using the [formGroup]=”todoForm”.

 todoForm = new FormGroup({
    item: new FormControl('MDT'),
    description: new FormControl('')
  });

Binding the control

We can replace the name property of input with formControlName. So that the data in the FormGroup will be automatically updated. and the template will look like

{{todoForm | json}}
<form [formGroup]="todoForm"   novalidation (ngSubmit)="OnSubmit()"  >
      <div class="form-group">
      <label>Title</label>
 <input type="text" required class="form-control" formControlName="item">
      </div>
      <div class="form-group ">
      <label>Description</label>
      <textarea class="form-control" formControlName="description" ></textarea>
      </div>
       <button  type="submit" class="btn btn-primary">Submit</button>
      </form>

The interpolation statement will display the data.

When ever the user change the data the {{todoForm | json}} will output the value and it is live data.

Now you know how to capture data in a Reactive form using formGroup and formControl.

A set form projects available in the Source-Code Page

These angular post may help you

[display posts tag=angular-form]

How to capture data in Angular form using Model

How to capture data from a Angular form using Model and ngModel


Form submission is an essential part of any commercial application. So lets learn about capturing data in Template Driven Form ( Regular Form) which is hard coded in template.

app.module import

We have to import FormsModule to app.module.ts as follows

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

Capturing the data in Template

Model

The very first thing we need to do is create Model class with following fields.

export class Todo {
    constructor(
        public item: string,
        public description: string
    ) { }
}

and in the component define property todoForm and initialize it as follows

todoForm = new Todo('New todo', 'some text');

Now we are ready to capture the data using ngModel binding ( property). Also create a reference variable (#item=”ngModel”)

 <form #todoForm="ngForm">
   {{todoForm | json}}
   <div class="form-group">
    <label>Title</label>
    <input type="text"  class="form-control" name="title" [ngModel]="todoForm.item" #item="ngModel" >
   </div> 
   <div class="form-group ">
    <label>Description</label>
    <textarea class="form-control" minlength="10" [ngModel]="todoForm.desc" #desc="ngModel" name="desc"></textarea>
  </div>
    <button type="submit" class="btn btn-primary">Submit</button>
 </form>

The interpolation statement will display the data.

We have problem in property binding ( [ngModel]), that the model not updated as the control value changes. So we need a two way binding ( [()]))

Two way binding

Two way binding can be applied by placing event binding in ngModel as follows

     [(ngModel)]="todoModel.item"

When ever the user change the data the {{todoForm | json}} will output the value and it is live data.

Now you know how to capture data in a form using a Model class.

A set form projects available in the Source-Code Page

These angular post may help you

[display posts tag=angular-form]

How to capture data in Angular form using `ngModel` and `FormsModule` ?

How to capture data from a Angular form using ngModel


Form submission is an essential part of any commercial application. So lets learn about capturing data in Template Driven Form ( Regular Form) which is hard coded in template.

app.module import

We have to import FormsModule to app.module.ts following

import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';

Capturing the data in Template

First step

For capturing the data we need to use the ngForm which is working behind scene. So let’s reference it in the form tag as follows

 <form #todoForm="ngForm">
   {{todoForm | json}}
   <div class="form-group">
    <label>Title</label>
    <input type="text"   required    class="form-control" name="title"  >
   </div> 
   <div class="form-group ">
    <label>Description</label>
    <textarea class="form-control" minlength="10" name="desc"></textarea>
  </div>
    <button type="submit" class="btn btn-primary">Submit</button>
 </form>

The interpolation statement will display the data.

Second step

We have to tell the ngForm which input field , need to bind. We can use ngModel to bind the input controls as follows

    <div class="form-group">
    <label>Title</label>
    <input type="text" required class="form-control" name="title" ngModel >
   </div> 
   <div class="form-group ">
    <label>Description</label>
    <textarea class="form-control" minlength="10" name="desc" ngModel></textarea>
  </div>

When ever the user change the data the {{todoForm | json}} will output the value and it is live data.

Now you know how to capture data from a form.

These angular post may help you

[display posts tag=angular-form]

How to handle exceptions in Angular service

How to create http service in angular for posting data to the server


A service in angular has special duties such as fetching and pushing data from the server and to the server. The service can be used by any components.

Handle exception

To hand service exceptions we need the following two libraraies

import {catchError} from 'rxjs/operators';
import { throwError } from 'rxjs';

In the service.ts file we need to handle the error using pipe function as follows

....
   Post(model : Model){
   return    this._http.post   ('http:\apiurl',model).pipe(catchError(this.ErrorHandler));
  }
  ErrorHandler(error: HttpErrorResponse): any {
    return throwError(error);
  }

Catching the error in component

For the receiving the error in a component , we need to create property then assign the error object to the property. So that we can bind it to the template.

...
    this._service.Post(this.data).subscribe((data: any) => console.log('Success', data), (error: any) => this.errorMsg = error.statusText);
  }

Don’t forget to visit the source code page

How to use service in angular

How to create http service in angular for posting data to the server


A service in angular has special duties such as fetching and pushing data from the server and to the server. The service can be used by any components.

Generate service

With following post you can quickly generate a service file which has special naming convention in Angularjs.

http request

Our service using a httpclient module to fetch data from the server. We need to import the library in

  • app.module.ts
  • list.service.ts

app.module.ts

In app.module we need to import the HttpClieneModule and also need to add the component in imports. For simplicity I skipped the rest of the code

...
import { HttpClientModule } from '@angular/common/http';
@NgModule({
 ....
  imports: [
    BrowserModule,  
    HttpClientModule
  ],
 ....
})
export class AppModule { }

list.Service.ts

In the service.ts file we need to import and inject the dependency in the constructor as follows

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
....
@Injectable({
  providedIn: 'root'
})

export class ListService {
 constructor(private _http: HttpClient) { }
  _url = 'http://localhost:3004/todo';  
  constructor(private _http: HttpClient) { }
   Post(model : Model){
   return    this._http.post<any>('http:\\apiurl',model)
}
  
}

In the service we created a function for Post data and make a call to POST API request.

Using the service in component

To use the service in a component we need to perform the following

  • Import the service
  • Add dependency in constructor
  • create a function handler
import { TodoService } from './todo.service';
....
export class AppComponent {
 
  data = new Model('title', 'some text');
  constructor(private _service: TodoService) { }
  eventHandler(): void {
    this._service.Post(this.data).subscribe((data: any) => console.log('Success', data), (error: any) => console.log('Error', error) );
  }

To get the response we have to subscribe to the service. A service example project is available on the source code page.

Don’t forget to visit the source code page