从Angular 2中的Click事件将对象加载到表单

时间:2017-06-14 02:06:27

标签: typescript angular2-forms angular-routing angular-reactive-forms

我是角度2的新手;我正在使用打字稿来编写组件,我有一个"产品"对象在登陆网站时,用户会看到所有产品的列表(来自RESTful端点的JSON数据)。如果该用户点击列表中的某个产品,则会将其带到"编辑"将该产品的所有详细信息填充到表单字段以供用户编辑的页面。我的问题是,如何在角度2中编程?我在网上看到的大多数例子都在与视图相同的页面(组件)上进行编辑。

  • 我的项目结构:
    • 产品型号
    • product.service 服务) - >从RESTful端点获取数据
    • product.component 组件) - >加载列表中的所有产品和显示
    • edit.component 组件) - >显示所选产品中的所有数据,也使用HTML
    • 中的反应形式控件
    • 使用angular 2 version 4

我正在考虑使用端点(例如/ api / product?id = xxx),但需要知道如何从product.component的选择中传递产品ID的参数

谢谢!

1 个答案:

答案 0 :(得分:1)

按照建议使用端点是去恕我直言的正确方法。 这需要几个步骤。

  1. 使用id参数
  2. 定义路线
    const routes: Routes = [
        { path: 'products', component: ProductComponent },
        { path: 'products/:id', component: EditProductComponent }
    ];
    

    2。在ProductComponent中单击调用正确的路径

    constructor(private router: Router, private service: ProductService) {}
    
    onClick(id: number) {
       this.router.navigate(['products', id]);
    }
    

    3。在EditProductComponent中从路径中检索id

    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
      }
    }