import {Component, HostListener, OnInit} from '@angular/core';
import {MenuItem, MessageService} from "primeng/api";
import {HttpClient} from "@angular/common/http";
import {ActivatedRoute, ParamMap, Router} from "@angular/router";
import {CategoryForm} from "./category-form";
@Component({
selector: 'app-articles-category-add-edit',
templateUrl: './category-add-edit.component.html',
providers: [MessageService]
})
export class CategoryAddEditComponent implements OnInit {
apiUrl = "/api/Articles/Categories";
loading = true;
model = new CategoryForm("", "");
home: MenuItem = {icon: 'pi pi-home', routerLink: '/admin/dashboard'};
paths = [
{label: '管理文章', routerLink: '/admin/articles'},
{label: '新建文章分类'}
];
categoryId?: string;
invalidNameReason = "";
pendingChanges = false;
saving = false;
constructor(private http: HttpClient,
private messageService: MessageService,
private route: ActivatedRoute, private router: Router) {
}
ngOnInit() {
this.route.paramMap.subscribe((params: ParamMap) => {
if (params.get('id') != "create") {
this.categoryId = params.get('id');
this.paths[1].label = "编辑文章分类 " + this.categoryId;
this.http.get(this.apiUrl + this.categoryId).subscribe(data => {
this.model = data as CategoryForm;
this.loading = false;
});
} else this.loading = false;
})
}
@HostListener('window:beforeunload')
canDeactivate() {
return !this.pendingChanges;
}
save() {
if (this.saving) return;
this.model.categoryName = this.model.categoryName.trim();
if (this.model.categoryName.length == 0) {
this.invalidNameReason = "分类名称不能为空。";
return;
}
this.model.categoryNameEn = this.model.categoryNameEn.trim();
this.saving = true;
const url = this.categoryId ? `${this.apiUrl}/${this.categoryId}` : this.apiUrl;
this.http[this.categoryId?"put":"post"](url, this.model).subscribe(
() => {
this.pendingChanges = false;
this.router.navigate(['../../'], {relativeTo: this.route});
},
() => {
this.messageService.add({severity: 'error', summary: '错误', detail: '保存失败。'});
this.saving = false;
}
);
}
}