【问题标题】:Create and Edit operations in angular以角度创建和编辑操作
【发布时间】:2017-12-22 14:15:19
【问题描述】:

我在angular 5 中实现了一个组件,它创建了我的foo 对象,它工作正常,但之后我想编辑它,所以我将编辑路径指向同一个组件:

const routes: Routes = [
  ...
  { path: 'foo/new', component: NewFooComponent },
  { path: 'foo/edit/:id', component: NewFooComponent },
  ...
];

我的问题是如何知道我的NewFooComponent.ts 是在foo/new 路径中还是在foo/edit/:id 中?

这也是最好的方法吗?

【问题讨论】:

  • 你不能测试一下你有没有id 吗?
  • 您可以尝试使用this answer中建议的方法获取id

标签: angular


【解决方案1】:

我要做的是将newedit 设置为参数并使用ActivatedRoute 检查参数

所以我会设置如下路线:

const routes: Routes = [
  ...
  { path: 'foo/:state', component: NewFooComponent },
  { path: 'foo/:state/:id', component: NewFooComponent },
  ...
];

然后做检查

constructor(public activatedRoute: ActivatedRoute) { }

ngOnInit() {
    this.activatedRoute.params.subscribe(
      params => {
        if(params['state'] === 'new') { ... } 
        else {...}
      }
    );
}

【讨论】:

  • 感谢您的解决方案,但如果 id 为空,检查 id 会很简单,您不觉得吗?
  • 当然,如果 id 仅在编辑模式下可用,那么是的,这更容易。我只是假设它不是。
【解决方案2】:

使用ActivatedRoute获取路由器参数导航idid属性存在于路径中

constructor(private route:ActivatedRoute){} 

ngOnInit(){
    // 'id' is the name of the route parameter
    if (this.route.snapshot.params['id']) { .... };
    else { ... }
}

【讨论】:

    【解决方案3】:

    我认为这是一个糟糕的设计决定,您的 NewFooComponent 现在正在创建和编辑某些东西,这违反了 SRP,所以也许您应该为编辑创建一个专用组件并共享模板是您试图避免仅创建一个组件的重复项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-03
      • 2015-08-13
      • 2021-07-01
      • 1970-01-01
      • 2019-04-07
      • 2016-01-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多