Angular basic application

Angular basic application

·

2 min read

To create a more interactive blog post-like experience, we can expand the application to include features such as routing for individual blog posts and a form for creating new posts. Let's break it down step by step:

  1. Set up routing: We'll use Angular Router to navigate between different components/pages.

  2. Create a service: We'll create a service to manage the data of the blog posts.

  3. Create components: We'll have components for displaying individual blog posts, listing all posts, and creating new posts.

Let's start with setting up routing:

First, install the Angular Router if you haven't already:

npm install @angular/router

Then, configure the routes in app-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { PostListComponent } from './post-list/post-list.component';
import { PostDetailComponent } from './post-detail/post-detail.component';
import { PostCreateComponent } from './post-create/post-create.component';

const routes: Routes = [
  { path: '', redirectTo: '/posts', pathMatch: 'full' },
  { path: 'posts', component: PostListComponent },
  { path: 'posts/:id', component: PostDetailComponent },
  { path: 'create', component: PostCreateComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Now, let's create components for listing posts, displaying a single post, and creating a new post:

ng generate component post-list
ng generate component post-detail
ng generate component post-create

Now, let's focus on the service for managing blog post data:

import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { Post } from './post.model';

@Injectable({
  providedIn: 'root'
})
export class PostService {
  private posts: Post[] = [];

  constructor() { }

  getPosts(): Observable<Post[]> {
    return of(this.posts);
  }

  getPostById(id: number): Observable<Post | undefined> {
    return of(this.posts.find(post => post.id === id));
  }

  addPost(post: Post): void {
    this.posts.push(post);
  }
}

In post.model.ts, define the Post interface:

export interface Post {
  id: number;
  title: string;
  content: string;
}

In each component's TypeScript file, you'll need to inject the PostService and use it to retrieve or manipulate data as needed.

With these components, services, and routing in place, you can now create a blog post-like application where users can view existing posts, read individual posts, and create new posts.

Did you find this article valuable?

Support AM by becoming a sponsor. Any amount is appreciated!