关于angular:组件关系问题

2次阅读

共计 3288 个字符,预计需要花费 9 分钟才能阅读完成。

新增和列表组件关系

之前的我的项目的设计中,列表组件和新增组件是兄弟组件。

const routes: Routes = [
  {
    path: '',
    component: IndexComponent
  },
  {
    path: 'add',
    component: VehicleAddComponent,
  },
  {
    path: 'edit/:id',
    component: VehicleEditComponent,
  },
];
  • 开始时,位于列表组件 index。
  • 点击新增,跳到 add 路由,此时加载 add 组件,并且 index 组件销毁。
  • 新增实现后,须要回跳到 index 组件。此时须要从新加载 index 组件,显示第一页的内容。

这样就会导致一个问题,假如原来处在第二页进行编辑或新增,当操作实现之后,并没有回跳到原来的页面。而是加载第一页的内容。


基与这个问题,咱们能够尝试把 新增 编辑 组件变成 列表 子组件

同时,咱们须要解决 新增或编辑的内容,不能实时的反馈到父组件中 这个问题。

indexComponet:

@Component({
  selector: 'app-project',
  templateUrl: './index.component.html',
  styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {component = 'index' as 'index' | 'add';}

index.html:

<app-add *ngIf="component ==='add'"(isFinish)="onAddFinish($event)"></app-add>


<div class="mt-3" *ngIf="component ==='index'">
<button thyButton="success" type="button" (click)="component ='add'">New Project</button>

    // index 组件内容
</div>

次要思路就是定义 componet 变量,当值为 ’index’ 时,显示列表内容,当值为 ‘add’ 时,
显示列表组件的内容。

同时,在子组件中设置 @Output(),当创立实现后,弹射该实体值。

AddComponent:

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.css']
})
export class AddComponent implements OnInit {@Output()
  isFinish = new EventEmitter<Project | null>();

 onSubmit(xxx: xxx) {this.projectService.save(xxx)
      .subscribe({
        next: project => {this.notifyService.success('创立胜利!');
          this.isFinish.emit(project);
        },
        error: err => {console.log(err);
        }
      })
  }

  /**
   * 返回
   */
  backWard() {this.isFinish.emit(null);
  }

indexController:

接管弹射值,若弹射实体,表明新增实现,更新到列表中。若为 null,则表明是返回,返回 index 界面。

/**
   * 新增组件实现后,更新到列表组件中
   * @param $event
   */
  onAddFinish($event: Project | null) {if($event) {this.pageData.content.push($event);
    }
    this.component = 'index';
  }

这样就可能在不从新加载列表组件的状况下,实现新增操作。

NGXS

通过老师的的领导,尝试应用 NGXS 来进行, 状态治理。

Ngxs 外围概念:

  • Store: 全局状态容器,操作调度程序和选择器
  • Actions: 形容要采取的操作及其关联元数据的类
  • State: 状态的类定义
  • Selects: 状态选择器

通过看官网文档,和查阅相干材料。大略是如下的样子:

一: 注册

  • 在 app.module.ts 中注册,NgxsModule.forRoot([ZoosState]) 即可

二:定义 Action

新建一个文件 action 文件。

新建 action 定义

import {Project} from '../../../entity/project';

export class AddProject {static readonly type = '[project] addProject';
  constructor(public project: Project) {}}

三:新建 State
State 是定义状态容器的类。

这里定义一个状态,它将监听一个 addProject 动作。



export interface ProjectModel {project: Project}

@State<ProjectModel>({
  name: 'project',
  defaults: {project: {} as Project
  },
})
@Injectable() // 也能够依赖注入
export class ProjectState {@Selector()
  static getProject(state: ProjectModel) {return state.project;}

  constructor(private projectService: ProjectService) {}

  @Action(AddProject)
  addProject(context: StateContext<Project>, action: AddProject) {const {project} = action;

    return this.projectService.saveByToken(project.projectToken).pipe(
      tap(project => {context.patchState(project)
      })
    )
  }

}

四:派发 dispatch

export class AddComponent implements OnInit {onSubmit(formGroup: FormGroup) {
    const newProject = {projectToken: formGroup.get(this.formKeys.projectToken)?.value,
    } as Project;

    
    this.store.dispatch(new AddProject(newProject))
      .subscribe({next: (project)=> {console.log(project);
        }
      })
  }
}

大抵的流程是这样,但可能因为某些中央不太熟悉,写错了,最初数据没能进去。

感想:
因为以前的开发方法不太一样,所以会感觉到有一些难了解。还没有齐全了解它的概念的用法。

subscribe 的扭转

另外值得注意的就是新版本中弃用了该 subscribe 办法的某些签名,

这种弃用是在 RxJS 6.4 中引入的。

弃用了所有 subscribe 须要超过 1 个参数的签名, 也弃用了仅传递 error 回调的签名。

目前把参数都写到一个大括号中:

this.labelService.update(this.label.id, newLabel)
      .subscribe({
        next: label => {this.notifyService.success(`label edit success`);
        },
        error: err => {console.log(err);
          this.notifyService.error('申请失败', err);
        }
      })

相似这种模式。

of([1,2,3]).subscribe({next: (v) => console.log(v),
    error: (e) => console.error(e),
    complete: () => console.info('complete') 
})
正文完
 0