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

Display responsive input field based on selected option in ionic2 dropdown menu

When the user selects 'Other' from the dropdown menu using Ionic2 and Angular2, I want to provide them with an option to enter their profession. Here is a visual representation of the select box: Below is the code snippet for achieving this fun ...

What is the reason WebPack is missing from the Visual Studio 2017 Dot Net Core 2.1 & Angular template?

Webpack 4 has introduced numerous enhancements, such as increased speed of up to 98% with minimal configuration. Interestingly, while Visual Studio 2017 with dot net core + angular 4 included webpack in the template, a recent project created in VS 2017 w ...

My Angular custom libraries are having issues with the typing paths. Can anyone help me troubleshoot what I might be doing

After successfully creating my first custom Angular library using ng-packagr, I encountered an issue where the built library contained relative paths specific to my local machine. This posed a problem as these paths would not work for anyone else trying to ...

Updating the color of specific buttons using ngFor in Typescript and Angular 8

I have successfully implemented a feature where text is displayed word by word using an ngFor directive. Within the ngFor loop, there is an if-else statement that determines whether each word should be displayed as a <span> or a <button>. Now, ...

How can I apply a class to an Angular tag that already has existing CSS classes in the HTML template?

I am looking to write code similar to the following: Note: I do not have control over the classes in the class property (style13, style121, style541), but I want to add another class from a variable in the TypeScript. For example: <div class="styl ...

How to pass a single property as a prop in TypeScript when working with React

I have a main component with a parent-child relationship and I am looking for a way to pass only the product name property as props to my "Title" component. This way, I can avoid having to iterate through the information in my child component. To better i ...

Table pagination in Mat is experiencing overflow, and the button styles have also been customized for a unique look

I implemented a mat paginator feature, however, I am facing an issue where the alignment of items per page options is not correct. Below is the snippet from component.html file: <div class="table-responsive" *ngIf="resultssummaries"> &l ...

The name 'XXX' is nowhere to be found

I encountered an error stating "Cannot find name 'Calendar Component'" while attempting to add a route to a component from another module in my app.module.ts file. Below is the content of my app.module.ts file: // Importing Modules // import {B ...

Error message occurs during compilation of basic Vue file in Webpack

When I execute webpack watch in the VS2017 task runner, it displays the following error: ERROR in ./wwwroot/js/src/App.vue Module build failed: SyntaxError: Unexpected token { at exports.runInThisContext (vm.js:53:16) at Module._compile (module.js:373:25) ...

Enhancing Angular 17 performance - Integration of AWS URL repeated in server-side rendering for improved HTTP response

In an attempt to transform the API response, I am adding the AWS S3 bucket URL as a prefix to the banner URL from the API side. The transformation works correctly without SSR (Server-Side Rendering). However, when I tested it with SSR, the URL prefix was a ...

The JWT token contains a HasGroup parameter set to true, however, the roles values are missing from the claims

I recently made some changes to the group claims in my Azure AD app's token configuration. While I can see a value of hasGroup: true in my token, I am not able to view the actual list of groups. Can someone please assist me with this? "claims&qu ...

Definition file for Typescript d.ts that includes optional properties in a function

Within my code, I have a function that offers different results based on specified options. These options dictate the type of return value. The function is currently written in plain JavaScript and I am looking to provide it with types using an index.d.ts ...

Ways to stop dialog from disappearing in Reactjs

This code snippet demonstrates the implementation of a popup with buttons, where clicking the cancel button triggers a confirmation dialog. To make the popup disappear when clicked outside of it, the following event handling is employed: const popupRef = ...

Angular - The differ is unable to find support for the object 'Item One' which is of type 'string'. NgFor is only able to bind to Iterables like Arrays and not individual objects

Many questions on StackOverflow share similarities with this one, but I have not been able to find a solution that fits my issue. My code functions correctly when attempting to populate items in a "Select" control. It successfully retrieves data if the it ...

The error at core.js line 4442: TypeError - Unable to access the 'trim' property of an undefined value

I encountered an issue with the 'trim' function in my Angular Node MySQL CRUD Application core.js:4442 ERROR TypeError: Cannot read property 'trim' of undefined at AdmissionListComponent.post (admission-list.component.ts:30) at Admissi ...

Encountering a service call error during the execution of Angular 2 unit tests using Jasmine

Struggling with testing an angular service, my TypeScript code seems correct but I keep getting an error in my test cases for "this.someFunction.show()" not being a function, even though it exists in my actual service. Here is what I'm attempting to d ...

reactjs: disable a specific eslint rule

I'm trying to figure out how to disable the "no-unused-vars" rule specifically for TypeScript interfaces. Here's a code snippet where I'm getting a warning: export type IKeoTableColumn<T> = { id: T; align: 'left' | ' ...

Can you explain Angular's "rule of unidirectional data flow" to me?

The concept of Angular's "unidirectional data flow rule" is mentioned throughout various sections of the Angular documentation, yet a clear and concise definition of this rule is nowhere to be found. After thorough research, I discovered two somewhat ...

Guide on how to "attach" the routes of an Angular 2 module to a specific location within the routing structure

Let's consider a scenario where the main routing module is defined as follows: // app-routing.module.ts const appRoutes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'auth', ...

Experiencing difficulties with the mat-card component in my Angular project

My goal is to implement a login page within my Angular application. Here's the code I've written: <mat-card class="login"> <mat-card-content> <div class="example-small-box mat-elevation-z4"> ...