Angular 传递:id到服务
对我来说,这是一个很简单的问题 我正在使用WordPress REST API并尝试使用显示类别中的帖子列表,我的问题是我不确定如何将ID从类别列表传递到posts-service.ts。将列出文章的组件称为category-single.component.tsAngular 传递:id到服务,angular,typescript,wordpress-rest-api,Angular,Typescript,Wordpress Rest Api,对我来说,这是一个很简单的问题 我正在使用WordPress REST API并尝试使用显示类别中的帖子列表,我的问题是我不确定如何将ID从类别列表传递到posts-service.ts。将列出文章的组件称为category-single.component.ts categories-list.component.html app-routing.module.ts posts.service.ts 导出类PostsService{ 私有wpBase=”http://base.loc
categories-list.component.html
app-routing.module.ts
posts.service.ts
导出类PostsService{
私有wpBase=”http://base.local/wp-json/wp/v2/";
构造函数(私有http:http){}
getPostList():可观察{
返回此文件。http
.get(this.wpBase+`posts?categories={ID在这里}`)
.map((res:Response)=>res.json());
}
}
一旦重定向到desire route,您需要获取route参数,如下所示
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{//Legend!现在似乎对我起作用了。在category-single.component.ts中这样做正确吗?getPostList(id){this.postservice.getPostList(id).subscribe(res=>{this.posts=res;}
{let id=+params['id'];/(+)将字符串'id'转换为数字this.getPostList(id);};
这是什么?getPostList(id)
在categorysinglecomponent.ts
中做什么将保留在PostsService
服务中。从本供参考的注释中写入代码,您可以使用键盘上的backtick。您不需要使用
标记。此外,如果它解决了您的问题,您可以接受答案,这样对未来的读者会有帮助。我告诉您这一点,因为您似乎是新手ow.getPostList应该从posts.services.ts获得响应,这样我就可以去:- {post.id}
我忘了添加,我有posts:post[];
在我的分类中-single.component.ts。除此之外,非常感谢你提供了上述代码,让我看到了我还没有学会的代码!
{
path: 'category/:id',
component: CategorySingleComponent
}
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());
}