Anthony Hubble Anthony Hubble - 1 month ago 14
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.




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

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


}


Also,

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

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

}
Comments