This is the codeAbility Sharing Platform! Learn more about the codeAbility Sharing Platform.

Skip to content
Snippets Groups Projects
bookmarks-update.component.ts 2.58 KiB
Newer Older
import { Component, OnInit } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import { FormBuilder, Validators } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs';

import { IUserWatchList, UserWatchList } from 'app/shared/model/user-watch-list.model';
import { UserWatchListService } from 'app/entities/user-watch-list/user-watch-list.service';
import { IUser } from 'app/core/user/user.model';
import { UserService } from 'app/core/user/user.service';

@Component({
  selector: 'jhi-user-watch-list-update',
  templateUrl: './bookmarks-update.component.html',
})
export class UserWatchListUpdateComponent implements OnInit {
  isSaving = false;
  users: IUser[] = [];

  editForm = this.fb.group({
    id: [],
    name: [null, [Validators.required, Validators.minLength(1)]],
Michael Breu's avatar
Michael Breu committed
    userIdId: [null],
  });

  constructor(
    protected userWatchListService: UserWatchListService,
    protected userService: UserService,
    protected activatedRoute: ActivatedRoute,
    private fb: FormBuilder
  ) {}

  ngOnInit(): void {
    this.activatedRoute.data.subscribe(({ userWatchList }) => {
      this.updateForm(userWatchList);

      this.userService.query().subscribe((res: HttpResponse<IUser[]>) => (this.users = res.body || []));
    });
  }

  updateForm(userWatchList: IUserWatchList): void {
    this.editForm.patchValue({
      id: userWatchList.id,
      name: userWatchList.name,
      userIdId: userWatchList.userIdId,
    });
  }

  previousState(): void {
    window.history.back();
  }

  save(): void {
    this.isSaving = true;
    const userWatchList = this.createFromForm();
    if (userWatchList.id !== undefined) {
      this.subscribeToSaveResponse(this.userWatchListService.update(userWatchList));
    } else {
      this.subscribeToSaveResponse(this.userWatchListService.create(userWatchList));
    }
  }

  private createFromForm(): IUserWatchList {
    return {
      ...new UserWatchList(),
      id: this.editForm.get(['id'])!.value,
      name: this.editForm.get(['name'])!.value,
      userIdId: this.editForm.get(['userIdId'])!.value,
    };
  }

  protected subscribeToSaveResponse(result: Observable<HttpResponse<IUserWatchList>>): void {
    result.subscribe(
      () => this.onSaveSuccess(),
      () => this.onSaveError()
    );
  }

  protected onSaveSuccess(): void {
    this.isSaving = false;
    this.previousState();
  }

  protected onSaveError(): void {
    this.isSaving = false;
  }

  trackById(index: number, item: IUser): any {
    return item.id;
  }
}