传递:id到服务

时间:2016-10-11 06:03:01

标签: angular typescript wordpress-rest-api

对我而言,早期的角度日,希望是简单的问题。

我正在使用WordPress REST API并尝试使用this显示某个类别中的帖子列表,我的问题是我不确定如何将ID从类别列表传递到帖子 - service.ts将列出文章的组件称为category-single.component.ts。

类别-list.component.html

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

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

  }

}

1 个答案:

答案 0 :(得分:1)

重定向到所需路线后,您需要获取路线参数,如下所示,

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

}