Anthony Hubble Anthony Hubble - 6 months ago 46
TypeScript Question

Passing :id to Service

Early Angular days for me, hopefully simple question.

I'm using the WordPress REST API and trying to display a list of posts from a category using posts?categories={ID HERE}, my issue is that I'm not sure how to pass the ID from categories-list to posts-service.ts the component that will list the articles is called category-single.component.ts.


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


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


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


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());




Once you redirect to desire route, you need to fetch route parameter as shown 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()...



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

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