Sending the :id parameter to the Service component

In the early days of my Angular journey, I have a simple question.

Currently, I am utilizing the WordPress REST API to showcase a list of posts from a specific category by using posts?categories={ID HERE}. However, I am facing an issue in passing the ID from the categories-list to the posts-service.ts file. The component responsible for listing the articles is called category-single.component.ts.


categories-list.component.html

<ul *ngFor="let category of categories">
  <li><a (click)="selectCategory(category.id)">{{category.name}}</a>
  </li>
</ul>

categories-list.component.ts

selectCategory(id) {
  this.router.navigate(['/category', id]);
}

app-routing.module.ts

{
  path: 'category/:id',
  component: CategorySingleComponent
}

posts.service.ts

export class PostsService {

  private _wpBase = "http://base.local/wp-json/wp/v2/";

  constructor(private http: Http) {}

  getPostList(): Observable < Post[] > {

    return this.http
      .get(this._wpBase + `posts?categories={ID GOES HERE}`)
      .map((res: Response) => res.json());

  }

}

Answer №1

When you are redirected to a specific route, it is important to extract the route parameter as illustrated below,

export class CategorySingleComponent{

   constructor(  private route: ActivatedRoute,  
                 private router: Router,
                 private postsService : PostsService  ) {}

   ngOnInit() {
     this.route.params.forEach((params: Params) => {
        let id = +params['id']; // (+) converts string 'id' to a number
        // this.postsService.getPostList(id).subscribe()...
      });
   }


}


Additionally,

getPostList(id:number): Observable < Post[] > {        //<<<===changed

    return this.http
      .get(this._wpBase + `posts?categories={ID GOES HERE}`)
      .map((res: Response) => res.json());

}

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

Having trouble compiling a Vue.js application with TypeScript project references?

I'm exploring the implementation of Typescript project references to develop a Vue application within a monorepo. The current structure of my projects is outlined below: client/ package.json tsconfig.json src/ ... server/ package.json t ...

Tips for changing a function signature from an external TypeScript library

Is it possible to replace the function signature of an external package with custom types? Imagine using an external package called translationpackage and wanting to utilize its translate function. The original function signature from the package is: // ...

Angular 6 form controls with reactive elements

Looking to create a simple homepage using Angular 6. One of the features will include tests for prime factorization and leap years, implemented with reactive forms for validation. However, I am facing an issue where I cannot execute both functions simultan ...

How can I enable editing for specific cells in Angular ag-grid?

How can I make certain cells in a column editable in angular ag-grid? I have a grid with a column named "status" which is a dropdown field and should only be editable for specific initial values. The dropdown options for the Status column are A, B, C. When ...

Tips for effectively utilizing the Angular ngIf directive for toggling the visibility of elements

<div *ngFor = "let element of myElements, let i=index" [ngClass]="{'selected':element[i] == i}"> <li> Name: {{element.element.name}}</li> <li> Description: {{element.element.description}}</li ...

One parent contains two identical components, but the first component takes precedence over the second

Within my component, I have two subcomponents that are identical: <!-- Some code ... --> <app-upload-button #idBook [accept]="'image/*'" (loadend)="onImageLoaded('#this-idbook-preview')" > </app-upload-button> ...

Proper utilization of ngIf in conjunction with mat-cell

I am attempting to show a specific value only if the item possesses a certain property, but I keep seeing [object Object] instead. Here is my current method: <ng-container matColumnDef="name"> <th mat-header-cell *matHeaderCellDe ...

What steps can I take to fix the 'node module error' while deploying a project on Vercel?

While working with the world-countries package, I encountered an issue during deployment in Vercel. The error message indicated that a ';' was missing in the index.d.ts file of world-countries located in the node_module directory. Here is the ex ...

Upon executing the `npm start` command, the application experiences a crash

When I tried following the steps of the Angular quickstart guide, I encountered some errors after running "npm start". Here are the errors displayed: node_modules/@angular/common/src/directives/ng_class.d.ts(46,34): error TS2304: Cannot find name 'Se ...

Error message: Unable to associate with DIRECTIVE as it is not a recognized attribute of 'div'

Despite searching through similar questions about this error, I have not been able to find a solution. The issue arises with my highlight directive, which takes an input parameter index. Initially, the directive worked perfectly when declared within the m ...

How can I access a service without the need to import its provider module?

My goal is to grasp the concept of multiple NgModules in an angular application and how they interact, specifically focusing on importing a SharedModule for commonly used services into lazily loaded feature modules. Here's the sequence of steps I fol ...

Ways to enable Urql (typescript) to accept Vue reactive variables for queries generated using graphql-codegen

I'm currently developing a Vue project that involves using urql and graphql-codegen. When utilizing useQuery() in urql, it allows for the use of Vue reactive variables to make the query reactive and update accordingly when the variables change. The ...

Exploring ways to fetch an HTTP response using a TypeScript POST request

I have been looking at various questions, but unfortunately, none of them have provided the help I need. The typescript method I am currently working with is as follows: transferAmount(transfer: Transfer): Observable<number> { return this.http .po ...

Angular 6 Checkbox Selector - Filtering Made Easy

How can I filter a list of JSON objects (Products) by the 'category' variable using checkboxes? An example product object is shown below: { 'bikeId': 6, 'bikeName': 'Kids blue bike', 'bikeCode': ...

Encountering a 404 error when importing http/server in deno

The file named index.ts is located below import { serve } from "https://deno.land/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b0c3c4d4f0809e8186869e80">[email protected]</a>/http/server.ts"; function ...

Shift the Kid Element to an Alternate Holder

Currently, I am working on a project in Angular version 10. Within this app, there is a component that can be shared and will utilize the provided content through ng-content. Typically, this content will consist of a list of items such as divs or buttons. ...

Choose a Spot on the Open Layers map using a marker or icon

As a beginner in the world of Open Layers, I'm eager to learn how to utilize markers or icons to obtain user location. Additionally, I hope to harness the power of Angular to extract these location details. ...

When utilizing Monggose, Angular, and Node, a route containing the deleteOne method repeatedly reports that the object has been successfully deleted, despite the delete count remaining

I've encountered a similar issue to others, but their solutions didn't work for me. I'm working on a small MEAN app with mongoose and facing a problem when trying to delete a user or any other object stored in the collection. The route seems ...

Even if I set a small modal, the large one can still be visible in the background

I've been working on a small modal, but encountered an issue where the large modal remains visible in the background when the small one is displayed. Any suggestions on how to fix this? I made some updates to my code based on recommendations. Here is ...

In order for Angular jQuery click events to properly function, they must be triggered by a

My admin panel is built using jQuery and Bootstrap, and it functions properly when used outside of the Angular framework. However, after integrating jQuery and Bootstrap into an Angular project and configuring them, I noticed that I had to double click on ...