angular - ¿Cómo usar un parámetro de ruta como argumento para un método de servicio?
Estoy tratando de llevar los detalles del producto a la ruta de un solo producto. Por ahora tengo una ruta para un solo producto con un parámetro id y está funcionando bien
{ path: 'single-product/:id', component: SingleProductComponent }
y en el componente TypeScript :
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));
});
}
En la consola obtuve el producto correcto, pero ¿cómo puedo pasar los datos a la vista?
Respuesta #1
Primero lo primero:
Vamos a encapsular esa lógica de filtro en la clase de servicio:
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));
}
}
Ahora podemos volver al componente:
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
}
}
Ahora, en tu plantilla podrías usar un pequeño truco para acceder al valor más reciente en el flujo product$:
<ng-container *ngIf="product$ | async as product">
{{ product | json }}
// your template goes here
</ng-container>
Respuesta #2
Usa el siguiente código para implementarlo en tu componente:
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);
});
}
}
Ahora usa tus datos en tu plantilla HTML así (HTML de ejemplo):
<table>
<tr>
<td>Product Name</td>
<td>{{product.productName}}</td>
</tr>
</table>
