opt-cc/static/src/app/users/edit-user/edit-user.component.ts

136 lines
3.5 KiB
TypeScript

import {Component, ViewChild} from "@angular/core";
import {ActivatedRoute, Router} from "@angular/router";
import {Rank, Squad, User} from "../../models/model-interfaces";
import {UserService} from "../../services/army-management/user.service";
import {SquadService} from "../../services/army-management/squad.service";
import {RankService} from "../../services/army-management/rank.service";
import {Subscription} from "rxjs";
import {NgForm} from "@angular/forms";
@Component({
templateUrl: './edit-user.component.html',
styleUrls: ['./edit-user.component.css', '../../style/entry-form.css', '../../style/overview.css'],
})
export class EditUserComponent {
@ViewChild(NgForm) form: NgForm;
subscription: Subscription;
user: User = {username: '', squadId: '0', rankLvl: 0};
squads: Squad[] = [];
ranks: Rank[] = [];
showSuccessLabel = false;
ranksDisplay = 'none';
showErrorLabel = false;
error: string;
constructor(private router: Router,
private route: ActivatedRoute,
private userService: UserService,
private squadService: SquadService,
private rankService: RankService) {
}
ngOnInit() {
this.subscription = this.route.params
.map(params => params['id'])
.filter(id => id != undefined)
.flatMap(id => this.userService.getUser(id))
.subscribe(user => {
if (!user.squadId) {
user.squadId = "0";
this.ranksDisplay = 'none';
} else {
this.rankService.findRanks('', user.squadId.fraction).subscribe(ranks => {
this.ranks = ranks;
this.ranksDisplay = 'block';
});
}
this.user = user;
});
this.squadService.findSquads().subscribe(squads => {
this.squads = squads;
});
}
toggleRanks() {
if (this.user.squadId != '0') {
this.rankService.findRanks('', this.user.squadId.fraction).subscribe(
ranks => {
this.ranks = ranks;
this.ranksDisplay = 'block';
}
);
} else {
this.ranksDisplay = 'none';
}
}
saveUser(rankLevel) {
const updateObject = {
_id: this.user._id,
username: this.user.username,
rankLvl: rankLevel,
squadId: null
};
if (this.user.squadId._id !== '0') {
updateObject.squadId = this.user.squadId._id
}
if (this.user._id) {
this.userService.updateUser(updateObject)
.subscribe(user => {
if (!user.squad) {
user.squad = '0';
}
this.user = user;
this.showSuccessLabel = true;
setTimeout(() => {
this.showSuccessLabel = false;
}, 2000)
})
} else {
this.userService.submitUser(updateObject)
.subscribe(user => {
this.router.navigate(['..'], {relativeTo: this.route});
return true;
},
error => {
// duplicated user error message
if (error._body.includes('duplicate')) {
this.error = "Benutzername existiert bereits";
this.showErrorLabel = true;
setTimeout(() => {
this.showErrorLabel = false;
}, 5000);
}
})
}
}
cancel() {
this.router.navigate([this.user._id ? '../..' : '..'], {relativeTo: this.route});
return false;
}
/**
* compare ngValue with ngModel to assign selected element
*/
equals(o1: Squad, o2: Squad) {
if (o1 && o2) {
return o1._id === o2._id;
}
}
}