0

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.

  • My project structure:
    • product (model)
    • product.service (service) --> gets data from RESTful end point
    • product.component (component) --> loads all products and displays in list
    • edit.component (component) --> displays all data from selected product, also using reactive form controls within HTML
    • using angular 2 version 4

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!

1
  • I see something similar from another question here: stackoverflow.com/questions/35188060/… (yes I know linking is not best). Essentially it says @RouteConfig([ { component: MainComponent, path: "/:id" } ]), then this.router.navigate(['../Main', {id: 2}]);, then export class MainComponent { constructor(params: RouteParams) { let value: any = params.get("id"); } } --> thanks Vlado Tesanovic Commented Jun 14, 2017 at 2:31

1 Answer 1

2

Using the endpoint as you suggested is the right way to go IMHO. There are few steps which are needed for this.

  1. Define a route with id parameter
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
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.