Tips for displaying a detailed blog link in Angular

I am looking to display the details of a blog on a separate link in Angular. Within my Angular setup, I have a Blog file (blog.component.ts) and a service that retrieves all the blog data from an API backend created with Strapi. Each individual blog has a button that allows users to view the complete detail of the blog on a different link by referencing the unique ID, which is linked to 'pagina.component.ts'. To achieve this, I believe it's necessary to reference the ID of each blog.

Below is the code snippet from my blog.component.html where I already have a list of blogs:

<section class="articles">

  <article class="blue-article" *ngFor="let data of datas; index as i">
    <div class="articles-header">
      <time>{{ data.fecha }}</time>
      <span class="articles-header-tag-blue">{{ data.relevante }}</span>
      <span class="articles-header-category">
        <a href="#" class="blue" title="">{{ data.category.name }}</a>
      </span>
    </div>
    <div class="articles-content">
      <h1><a title="">{{ data.title }}</a></h1>
      <!--<img *ngIf="!data.image" class="foto" [src]="data.image.name" alt="foto">-->
      <div *ngIf="data.image">
        <img
          src="http://localhost:1337{{ data.image.url }}"
          alt="foto"
          width="100%"
        />
      </div>
      <p>
        {{ data.content }}
      </p>
      <h3>{{ data.description }}</h3>
    </div>
    <div class="articles-footer">
      <ul class="articles-footer-info">
        <li><a href="#" class="light-link" title=""><i class="pe-7s-comment"></i> 7 Replies</a>
        </li>
        <li><a href="#" class="light-link" title=""><i class="pe-7s-like"></i> 1221</a></li>
      </ul>

      <a [routerLink]="['./pagina', i]" class="btn">Read More</a>

    </div>
  </article>
</section>

Next, here is the content from my blog.component.ts file:


import { Component, OnInit } from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';
import { StrapiService } from '../../../services/strapi.service';

import { Router } from '@angular/router';

@Component({
  selector: 'app-blog',
  templateUrl: './blog.component.html',
  styleUrls: ['./blog.component.scss']
})
export class BlogComponent implements OnInit {

  datas:any=[];
  errores:string="";

  constructor(
    public strapiserv:StrapiService,
    private router: Router
  ) { }

  ngOnInit(): void {

    this.title.setTitle('Blog');

    this.strapiserv.getData().subscribe(res=>{

        this.datas= res as string[];

    }, error =>{
      console.log(error);
        if(error.status == 0){
            this.errores="Error Code: "+error.status+ "\n A client-side error or network error has occurred.";
        }else{
            this.errores="Error Code: "+error.status+"\n\n"+error.statusText;
        }
    })

  }


}

The Angular service I'm using is named 'strapi.service.ts' and here's its implementation:


import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})
export class StrapiService {

  REST_API: string ='http://localhost:1337/articles';
  
  httpHeaders = new HttpHeaders().set('Content-Type', 'application/json');
  constructor(private httpClient: HttpClient) { }


  getData():Observable<any>{
    console.log();
    let API=this.REST_API;
    return this.httpClient.get(API,{headers:this.httpHeaders}) .pipe(
      map((data:any) => { 
      
        return data;
      }), catchError( error => {
        return throwError(error);
      })
    )
    
  }

}

Finally, the code snippet from my pagina component where I intend to display the detailed blog content is provided below:


import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Router } from '@angular/router';

import { StrapiService } from '../../../../services/strapi.service';

@Component({
  selector: 'app-pagina',
  templateUrl: './pagina.component.html',
  styleUrls: ['./pagina.component.scss']
})
export class PaginaComponent implements OnInit {

  data:any = {};

  constructor( private activatedRoute: ActivatedRoute,
           private router: Router,
           public strapiserv:StrapiService
    ){ 

    this.activatedRoute.params.subscribe( params => {
      this.data = this.strapiserv.getData( params['id'] );
    });

  }

  ngOnInit(): void {
  }

}

The routes configured for my application are as follows:

const routes: Routes = [
    { path: 'blog', component: BlogComponent },
    { path: 'pagina/:id', component: PaginaComponent },
];

Answer №1

There are numerous issues with the approach you have taken:

The 'i' serves as an index for the loop, not the 'id' that you should be using. It seems like the 'id' is a property of data, so it's best to reference data.id

When utilizing [routerLink] (within brackets), there is no need for a relative path,

[routerLink]="['/pagina', data.id]"

Instead of:

[routerLink]="['./pagina',i]"

Finally, in your blog.component.ts file, you are receiving an array of objects, so there is no need to cast it as an array of strings. Simply use this.datas=res;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason behind TypeScript mandating the invocation of super() by the inheriting class, even when the parent class does not have

Just starting out with class-based programming, I've been tinkering with a TypeScript API. Here's the scenario: import { Router } from "express"; export default class BaseController { public router = Router(); } and then I create another cl ...

Incorporate a boolean value into Ionic storage (Ionic 4) by adding a JSON object

I am looking to enhance my storage system by adding a special favorite feature. I have the ability to add multiple favorites to my storage, but only one can be designated as my top favorite! Take a look at this image for a visual representation of what I h ...

Browsing Identical Groups of Multiple Selection Drop Downs Using Javascript

Is there a way to loop through multiple form elements iteratively in order to identify the selected items from a select multiple input? I am looking for a solution that allows me to determine which selection box is being operated on and then extract all t ...

The JSON file is not filling the options in the dropdown menu

procedure Add the objects from the dropdown into the dropdown menu. The Json file is located in root/ajax/.json and the working file is stored in root/.html. Problem: None of the objects from the JSON file are appearing in the dropdown menu. I attempted ...

Hiding timestamps on an interactive transcript: A step-by-step guide

I am in the process of creating personalized interactive ebooks based on a similar website found here: This website utilizes a VTT file along with an audio file. Although the JavaScript code requires time stamps, I would like to hide them for better read ...

Issue-free AJAX call to Neo4j database on local server with no 'Access-Control-Allow-Origin' problem

I'm currently working on a basic JavaScript AJAX request to connect from a MAMP server running at localhost:8888 to a Neo4j database running on localhost:7474. The issue I'm encountering is the following error message: XMLHttpRequest cannot l ...

What steps do I need to take to create an animation where an outline gradually becomes filled in

I've been experimenting with creating a loading animation inspired by the pre-loading animation on this website. My attempt using chat GPT resulted in an unexpected outcome where, instead of filling the SVG, it placed a black square on top of it. The ...

Switching CommonJS modules to an ESM syntax for better compatibility

I'm currently facing a challenge in grasping the process of importing CommonJS modules into an ESM syntax. Specifically, I am working with the library url-metadata. This library provides a top-level export as a callable function, which deviates from t ...

How can I showcase a Google donut chart using an array of data in a React application?

I have created a doughnut chart that is supposed to take an array as data. However, when I input the array, nothing shows up on the chart. How can I create a chart with array data? sum.js ... const arr = []; arr.push({ key: capitalizeEachFirst ...

Perform a bash command using PHP when an HTML button is clicked

Today, my brain seems to be on vacation. Currently, I have set up a Raspberry Pi with vlc running and connected to a mounted screen on the wall. There is a web page with simple controls to manage the pi, switch between different vlc streams, or stop stream ...

What could be causing the "Error: Cannot locate module 'html'" message to appear while executing a Node.js Express server?

I'm facing an issue while setting up a server for my HTML application. Whenever I try to access localhost:8080/map, I receive the following error message: Error: Cannot find module 'HTML'. Nonetheless, the main page at localhost:8080 is runn ...

I have added the same directive to both of my HTML files

Hello, I am facing an issue with a directive that I have included in two HTML files. The 'app' is set as ng-app. <dir auto=""></div> The code for the directive is as follows: app.directive("auto", function() { scope: { arr : ...

Tips for applying attributes to an element in Angular 2

My Directive is a straightforward implementation with the following code: import { Directive, OnInit, OnDestroy, ElementRef } from "@angular/core"; @Directive({ selector: "[Checker]" }) export class Checker { constructor(private e: ElementRef) { ...

Is it possible to achieve a fade effect in material-ui that truly hides the component instead of just disabling its visibility? If so, how can this be accomplished?

Currently, I am utilizing the component provided by material-ui, which can be found at material-ui. <Fade in={!randomizeFlag}> <Grid> <FormControlLabel control={<Switch onChange={this.handleStartValueFlag} & ...

Angular mistakenly uses the incorrect router-outlet

Encountering an issue with Angular routing. The main app has its own routing module, and there is a sub module with its own routing module and router-outlet. However, the routes defined in the submodule are being displayed using the root router outlet inst ...

Instructions for setting 0 as a valid value in Html code and displaying it

I have a query regarding HTML code within an Angular app. My inquiry is, is there an alternative method to check for null or undefined values in an ngIf statement? The code I am working with looks like this: <div ngif= "value !== null and value ! ...

Updating variable values using buttons in PHP and Javascript

I've implemented a like/unlike button along with a field displaying the number of likes. The code below uses PHP and HTML to echo the variable that represents the total number of likes: PHP-HTML: <span>likes: <?php echo $row['likes&apo ...

What's the best way to align several buttons in the center of the screen horizontally?

I'm struggling to properly align divs with images inside another div. My goal is to insert buttons into my HTML and use jQuery to center them automatically, but I can't seem to get it right. You can view the fiddle I've created here: http:/ ...

Tips on containing the reach of a function in JavaScript/jQuery

I have a scenario where I have multiple .js files linked on the page, each containing functions with the same name. For example: first.js function DisplayContent(data,$target) // data is string { $target.html('<span>'+ data +'&l ...

What is causing the error message 'Unexpected use of 'location' no-restricted-globals'?

When working on my reactjs code, I encountered the following issue: const { children, location: { pathname }, } = this.props; let path = location.pathname; I am also utilizing the react router module in this component. Anyone have suggestions on how ...