代码之家  ›  专栏  ›  技术社区  ›  Yahya Essam

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

  •  2
  • Yahya Essam  · 技术社区  · 7 年前

    我正在尝试将产品详细信息转换为单一产品的路线。 目前为止 我有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 回复  |  直到 7 年前
        1
  •  2
  •   Jota.Toledo    7 年前

    第一件事第一:

    让我们在服务类中封装该筛选器逻辑:

    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>
    
        2
  •  1
  •   Sandip Jaiswal    7 年前

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

     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>