Reputation: 1833
I am new to angular 2; I am using typescript to program the components, I have a "product" object where upon landing to the website, the user sees a list of all products (JSON data coming from a RESTful endpoint). If that user clicks on one of the products from the list, it will take them to an "edit" page where all the details of that product is populated into form fields for the user to edit. My question is, how can I program this in angular 2? Most examples I see online do the editing on the same page (component) as the view.
I am thinking of using the endpoint (e.g. /api/product?id=xxx) but need to know how to pass the parameter of the product id from the selection made from the product.component
Thanks!
Upvotes: 0
Views: 763
Reputation: 6627
Using the endpoint as you suggested is the right way to go IMHO. There are few steps which are needed for this.
const routes: Routes = [
{ path: 'products', component: ProductComponent },
{ path: 'products/:id', component: EditProductComponent }
];
2. Call proper route on click in ProductComponent
constructor(private router: Router, private service: ProductService) {}
onClick(id: number) {
this.router.navigate(['products', id]);
}
3. Retrieve id from route in EditProductComponent
constructor(private activatedRoute: ActivatedRoute,
private service: ProductService) {}
ngOnInit() {
const id = this.activatedRoute.snapshot.params['id'];
if (id) {
// get product data by calling endpoint with provided id
// e.g. this.service.getProduct(id).subscribe...
} else {
// throw some notification to user
}
}
Upvotes: 2