【问题标题】:Passing :id to Service将 :id 传递给服务
【发布时间】:2016-10-11 06:03:00
【问题描述】:

对我来说早期的 Angular 日子,希望是简单的问题。

我正在使用 WordPress REST API 并尝试显示来自使用 posts?categories={ID HERE} 的类别的帖子列表,我的问题是我不确定如何将 ID 从类别列表传递到帖子服务。 ts 将列出文章的组件称为 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());

  }

}

【问题讨论】:

    标签: angular typescript wordpress-rest-api


    【解决方案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());
    
    }
    

    【讨论】:

    • 传奇!似乎现在为我工作。这在 category-single.component.ts 中看起来是否正确? getPostList(id){ this.postsService .getPostList(id) .subscribe(res =&gt; { this.posts = res; }); } ngOnInit() { this.route.params.forEach((params: Params) =&gt; { let id = +params['id']; // (+) converts string 'id' to a number this.getPostList(id); });
    • 这是什么? getPostList(id)categorysinglecomponent.ts 中做了什么?
    • getPostList(id) 将保留在PostsService 服务中。从此仅供参考,在注释中编写代码,您可以使用键盘上的反引号。你不需要使用&lt;code&gt; 标签。
    • 此外,如果它解决了您的问题,您可以接受答案,以便对未来的读者有所帮助。我告诉你这个是因为你似乎是 stackoverflow 的新手。
    • getPostList 应该从posts.services.ts 得到响应,所以我可以去:&lt;ul *ngFor="let post of posts"&gt; &lt;li&gt;{{post.id}}&lt;/li&gt; &lt;/ul&gt; 我忘了添加,我的category-single.component.ts 中有posts: Post[];。除此之外,非常感谢上面的代码,让我大开眼界我没学过的代码!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 2013-08-08
    • 1970-01-01
    • 2011-09-25
    相关资源
    最近更新 更多