以角度创建和编辑操作

You*_*sef 0 angular

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

const routes: Routes = [
  ...
  { path: 'foo/new', component: NewFooComponent },
  { path: 'foo/edit/:id', component: NewFooComponent },
  ...
];
Run Code Online (Sandbox Code Playgroud)

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

它也是最好的方法吗?

You*_*esM 5

我会做的是设置像newedit作为一个参数和检查参数使用ActivatedRoute

所以我将按如下方式设置路线:

const routes: Routes = [
  ...
  { path: 'foo/:state', component: NewFooComponent },
  { path: 'foo/:state/:id', component: NewFooComponent },
  ...
];
Run Code Online (Sandbox Code Playgroud)

并通过做检查

constructor(public activatedRoute: ActivatedRoute) { }

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