如何使用route参数作为服务方法的参数?

时间:2018-01-09 12:43:56

标签: angular typescript rxjs angular-routing angular-services

我正在尝试将产品详细信息提供给单一产品的路线。 目前 我有一个带有id参数的单个产品的路线,它工作正常

{ path: 'single-product/:id', component: SingleProductComponent }

并在组件打字稿中:

 id: string;
 private mainSub: any;
 public ngOnInit(): void {
  this.mainSub = this.route.params.subscribe(params => {
     this.id = params['id'];
  }
   this.productsService
    .all()
    .map(res => res.filter(item => item.id === this.id))
    .subscribe(resp => console.log(resp));      
 });
 }

在控制台中我得到了正确的产品,但如何才能将数据输入到视图中?

2 个答案:

答案 0 :(得分:2)

首先要做的事情:

让我们在服务类中封装过滤器逻辑:

export interface Product {
 // define the properties for your product
}

@Inject()
export class ProductService {
 ....
 // constructor injetction and other methods
 ....

 all(): Observable<Product[]>{
   // implementation
 }

 getById(id:string): Observable<Product> {
   // or maybe could your backend offer an endpoint that does this for you?
   // something like `root/api/products/:id`;
   return this.all().map(products => products.find(product => product.id === id));
 }
}

现在我们可以回到组件:

import 'rxjs/add/operator/switchMap'; // Maybe replace with lettable operators

@Component({...})
export class FooComponent {
 product$: Observable<Product>;
 constructor(private _route: ActivatedRoute, private _productService: ProductService){
    this.product$ = _route.paramMap
       .map(params => params.get('id')) // maps the route params. map to the id key
       .switchMap(id => _productService.getById(id));// change the main stream to the stream returned by the service
 }
}

现在,在您的模板中,您可以使用一个小技巧来访问product$流中的最新值:

<ng-container *ngIf="product$ | async as product">
   {{ product | json }}
   // your template goes here
</ng-container>

答案 1 :(得分:1)

使用以下代码在您的组件中实现:

 id: string;
 product: any;
 private mainSub: any;
 public ngOnInit(): void {
  this.mainSub = this.route.params.subscribe(params => {
     // I used + sign if id is number otherwise remove it
     this.id = +params['id'];
     this.productsService
      .all()
      .map(res => res.find(item => item.id === this.id))
      .subscribe(resp => this.product = resp);      
    });
  }
 }

现在在你的html模板中使用你的数据(虚拟html):

<table>
  <tr>
    <td>Product Name</td>
    <td>{{product.productName}}</td>
  </tr>
</table>