Part -3: Building a Single Page Application (SPA) with Angular and Rails

Raghavendra S

Part 3: Integrating Angular with Rails

We’ll now connect the Angular frontend to the Rails backend.

Step 1: Set Up an Angular Service

Generate a service to handle API requests:

ng generate service services/article

Update the article.service.ts file:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '../../environments/environment';

@Injectable({ providedIn: 'root' })
export class ArticleService {
private apiUrl = `${environment.apiUrl}/articles`;

constructor(private http: HttpClient) {}

getArticles(): Observable<Article[]> {
return this.http.get<Article[]>(this.apiUrl);
}

createArticle(article: Article): Observable<Article> {
return this.http.post<Article>(this.apiUrl, article);
}
}

Step 2: Display Data in Angular Components

Update the ArticlesComponent to fetch and display articles:

import { Component, OnInit } from '@angular/core';
import { ArticleService } from '../services/article.service';

@Component({
selector: 'app-articles',
templateUrl: './articles.component.html',
styleUrls: ['./articles.component.css']
})
export class ArticlesComponent implements OnInit {
articles: Article[] = [];

constructor(private articleService: ArticleService) {}

ngOnInit(): void {
this.articleService.getArticles().subscribe(data => {
this.articles = data;
});
}
}

Update articles.component.html to display articles:

<div *ngFor="let article of articles">
<h2>{{ article.title }}</h2>
<p>{{ article.content }}</p>
</div>

Continued in Part 4..

Sign up to discover human stories that deepen your understanding of the world.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Raghavendra S
Raghavendra S

Written by Raghavendra S

Artificial enthusiast. Rubyist.

No responses yet

Write a response