Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {Component, OnInit} from "@angular/core";
- import { AuthService } from "../../shared/auth.service";
- import {User} from "../../shared/user.interface";
- import {ROUTER_DIRECTIVES} from "@angular/router";
- import {UserItemComponent} from "./user-item.component";
- import {PaginatePipe, PaginationControlsCmp, PaginationService} from 'ng2-pagination';
- @Component({
- moduleId: module.id,
- selector: 'rb-users-list',
- templateUrl: 'users-list.component.html',
- directives: [UserItemComponent, ROUTER_DIRECTIVES, PaginationControlsCmp],
- pipes: [PaginatePipe],
- providers: [AuthService, PaginationService, UserItemComponent]
- })
- export class UsersListComponent implements OnInit {
- users: User[] = [];
- constructor(private authService: AuthService) {}
- ngOnInit() {
- this.getUsers();
- }
- getNotification(evt) {
- if(evt){
- this.getUsers();
- console.log('Pobrano użytkowników');
- }
- }
- getUsers() {
- //noinspection TypeScriptUnresolvedFunction
- this.authService.getDataUsers();
- this.authService.usersChanged.subscribe(
- (data: User[]) => {
- this.users = data;
- }
- );
- }
- }
- -------UserListComponent html-------
- <div class="row">
- <div class="col-xs-12">
- <a class="btn btn-success" [routerLink]="['new']">New user</a>
- </div>
- <div class="row">
- <div class="col-xs-12">
- <ul class="list-group">
- <rb-user-item (notifyParent)="getNotification($event)" *ngFor="let user of users | paginate: { itemsPerPage: 3, currentPage: page }; let i = index" [user]="user" [userId]="i"></rb-user-item>
- </ul>
- <div class="is-text-centered">
- <pagination-controls (pageChange)="page = $event"></pagination-controls>
- </div>
- </div>
- </div>
- import { Component, OnInit, OnDestroy } from '@angular/core';
- import { ActivatedRoute, Router } from "@angular/router";
- import { Subscription } from "rxjs/Rx";
- import {
- FormArray,
- FormGroup,
- FormControl,
- Validators,
- FormBuilder,
- REACTIVE_FORM_DIRECTIVES
- } from "@angular/forms";
- import {User} from "../../shared/user.interface";
- import {AuthService} from "../../shared/auth.service";
- @Component({
- moduleId: module.id,
- selector: 'rb-user-edit',
- templateUrl: 'user-edit.component.html',
- styles: [],
- directives: [REACTIVE_FORM_DIRECTIVES]
- })
- export class UserEditComponent implements OnInit, OnDestroy {
- userForm: FormGroup;
- error = false;
- errorMessage = '';
- errors: any;
- errorName: string;
- errorEmail: string;
- private userIndex: number;
- private user: User;
- private isNew = true;
- private subscription: Subscription;
- private formLoaded = false;
- constructor(private route: ActivatedRoute,
- private authService: AuthService,
- private formBuilder: FormBuilder,
- private router: Router) {}
- ngOnInit() {
- this.subscription = this.route.params.subscribe(
- (params: any) => {
- if (params.hasOwnProperty('id')) {
- this.isNew = false;
- this.userIndex = +params['id'];
- //noinspection TypeScriptUnresolvedFunction
- this.authService.getUser(this.userIndex).subscribe(
- data => {
- this.user = data;
- this.formLoaded = true;
- }
- );
- } else {
- this.isNew = true;
- this.user = null;
- }
- }
- );
- this.initForm(this.formLoaded);
- }
- onSubmit() {
- const newUser = this.userForm.value;
- newUser.id = this.userIndex;
- if (this.isNew) {
- this.authService.signupUserAdmin(this.userForm.value).subscribe(
- data => {
- this.errors = data;
- if( !this.errors.success ){
- this.errorName = this.errors.name;
- this.errorEmail = this.errors.email;
- }
- else{
- this.errorName = "";
- this.errorEmail = "";
- this.navigateBack();
- }
- }
- );
- } else {
- this.authService.editUser(newUser).subscribe(
- data => {
- this.errors = data;
- if( !this.errors.success ){
- this.errorName = this.errors.name;
- this.errorEmail = this.errors.email;
- }
- else{
- this.errorName = "";
- this.errorEmail = "";
- this.navigateBack();
- }
- }
- );
- }
- }
- onCancel() {
- this.navigateBack();
- }
- ngOnDestroy() {
- this.subscription.unsubscribe();
- }
- private navigateBack() {
- this.router.navigate(['users/']);
- }
- private initForm(formLoaded: boolean) {
- let userName = '';
- let userEmail = '';
- let userRole = '';
- if (!this.isNew && formLoaded) {
- userName = this.user.name;
- userEmail = this.user.email;
- userRole = this.user.role;
- }
- this.userForm = this.formBuilder.group({
- name: [userName, Validators.required],
- email: [userEmail, Validators.compose([
- Validators.required,
- this.isEmail
- ])],
- password: ['', Validators.required],
- confirmPassword: ['', Validators.compose([
- Validators.required,
- this.isEqualPassword.bind(this)
- ])],
- role: [userRole, Validators.required]
- });
- }
- isEmail(control: FormControl): {[s: string]: boolean} {
- if (!control.value.match(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/)) {
- return {noEmail: true};
- }
- }
- isEqualPassword(control: FormControl): {[s: string]: boolean} {
- if (!this.userForm) {
- return {passwordsNotMatch: true};
- }
- if (control.value !== this.userForm.controls['password'].value) {
- return {passwordsNotMatch: true};
- }
- }
- }
- -------UserEditComponent.html-------------------
- <div class="row">
- <div class="col-xs-12">
- <form [formGroup]="userForm" (ngSubmit)="onSubmit()">
- <div class="row">
- <div class="col-xs-12">
- <button type="submit" class="btn btn-success" [disabled]="!userForm.valid">Save</button>
- <a class="btn btn-danger" (click)="onCancel()">Cancel</a>
- </div>
- </div>
- <div class="form-group">
- <label for="email">Name</label>
- <input *ngIf="!user" formControlName="name" type="text" id="name" #name class="form-control">
- <input *ngIf="user" formControlName="name" type="text" id="name" #name class="form-control" [(ngModel)]="user.name">
- <span>{{errorName}}</span>
- </div>
- <div class="form-group">
- <label for="email">E-Mail</label>
- <input *ngIf="!user" formControlName="email" type="email" id="email" #email class="form-control">
- <input *ngIf="user" formControlName="email" type="email" id="email" #email class="form-control" [(ngModel)]="user.email">
- <span>{{errorEmail}}</span>
- </div>
- <div class="form-group">
- <label for="password">Password</label>
- <input formControlName="password" type="password" id="password" class="form-control">
- </div>
- <div class="form-group">
- <label for="confirm-password">Confirm Password</label>
- <input formControlName="confirmPassword" type="password" id="confirm-password" #confirmPassword class="form-control">
- <span *ngIf="!confirmPassword.pristine && confirmPassword.errors != null && confirmPassword.errors['passwordsNotMatch']">Passwords do not match</span>
- </div>
- <div class="form-group">
- <label for="role">Select list:</label>
- <select formControlName="role" class="form-control" id="role" #role>
- <option>user</option>
- <option>admin</option>
- </select>
- </div>
- </form>
- </div>
- </div>
- import { Injectable, EventEmitter} from "@angular/core";
- import { User } from "./user.interface";
- import { Router } from "@angular/router";
- import {Headers, Http, Response} from "@angular/http";
- import 'rxjs/Rx';
- import {AuthHttp, AuthConfig, AUTH_PROVIDERS, JwtHelper} from "angular2-jwt/angular2-jwt";
- @Injectable()
- export class AuthService {
- constructor(private router: Router, private http: Http) {}
- private userLoggedOut = new EventEmitter<any>();
- private jwtHelper: JwtHelper = new JwtHelper();
- usersChanged = new EventEmitter<User[]>();
- private users: User[] = [];
- signupUser(user: User){
- const body = JSON.stringify(user);
- const headers = new Headers();
- headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
- //noinspection TypeScriptUnresolvedFunction
- return this.http.post('../api/site/user/create/', body, {
- headers: headers
- }).map((data: Response) => data.json());
- }
- signupUserAdmin(user: User){
- user.token = localStorage.getItem('token');
- const body = JSON.stringify(user);
- const headers = new Headers();
- headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
- //noinspection TypeScriptUnresolvedFunction
- return this.http.post('../api/admin/users/create/', body, {
- headers: headers
- }).map((data: Response) => data.json());
- }
- signinUser(user: User) {
- const body = JSON.stringify(user);
- const headers = new Headers();
- headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
- //noinspection TypeScriptUnresolvedFunction
- return this.http.post('../api/site/user/login/', body, {
- headers: headers
- }).map((data: Response) => data.json());
- }
- getDataUsers() {
- const body = '{"token": "'+localStorage.getItem('token')+'"}';
- const headers = new Headers();
- headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
- //noinspection TypeScriptUnresolvedFunction
- return this.http.post('../api/admin/users/get', body, {
- headers: headers
- }).map((data: Response) => data.json())
- .subscribe((data: User[]) => {
- this.users = data;
- this.usersChanged.emit(this.users);
- });
- }
- getUser(id: Number) {
- const body = '{"token": "'+localStorage.getItem('token')+'"}';
- const headers = new Headers();
- headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
- //noinspection TypeScriptUnresolvedFunction
- return this.http.post('../api/admin/users/get/'+id, body, {
- headers: headers
- }).map((data: Response) => data.json());
- }
- editUser(user: User) {
- user.token = localStorage.getItem('token');
- const body = JSON.stringify(user);
- const headers = new Headers();
- headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
- this.usersChanged.emit(this.users);
- //noinspection TypeScriptUnresolvedFunction
- return this.http.post('../api/admin/users/update/', body, {
- headers: headers
- }).map((data: Response) => data.json());
- }
- deleteUser(user: User) {
- user.token = localStorage.getItem('token');
- const body = JSON.stringify(user);
- const headers = new Headers();
- headers.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
- console.log(user);
- //noinspection TypeScriptUnresolvedFunction
- return this.http.post('../api/admin/users/delete', body, {
- headers: headers
- }).map((data: Response) => data.json());
- }
- logout() {
- localStorage.removeItem('token');
- this.userLoggedOut.emit(null);
- this.router.navigate(['/signin']);
- }
- isAuthenticated(): boolean {
- return localStorage.getItem('token') !== null;
- }
- isAdmin(): boolean {
- var token = localStorage.getItem('token');
- if(token !== null)
- return this.jwtHelper.decodeToken(token).role == 'admin';
- else
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement