2017-08-10 20 views
0

angular2 applicaitonのログイン・コンポーネントを使用します。フォーム検証アンギュラ2

ログイン作業罰金だが、ユーザーが間違った/パスワードなしでログインすることができますし、間違ったときにエラー警告を与えません。サブスクリプションサービスや認証と連携検証にどのような形 ?

どれ可能な解決策は、素晴らしいことだ、感謝:)

活字体コンポーネント

import { Component, Output, EventEmitter} from '@angular/core'; 
import { Credentials } from './credentials'; 
import { AuthenticatedUser } from './authenticatedUser'; 
import { Http, Headers, RequestOptions } from '@angular/http'; 
import { CapitalizePipe } from './capitalize.pipe'; 
import { SubscriptionService } from './subscription.service'; 
import { Router, ActivatedRoute } from '@angular/router'; 

@Component({ 
    selector: 'login', 
    templateUrl: 'login.component.html', 
    styleUrls: [ 'login.component.css' ] 
}) 

export class LoginComponent { 
    TOKEN_KEY = "loginToken"; 
    ADMIN_KEY = "adminToken"; 
    USER_KEY = "userToken"; 


    public credentials; 
    public authenticatedUser: AuthenticatedUser; 
    loggedIn = false; 

    @Output() notify: EventEmitter<boolean> = new EventEmitter<boolean>(); 

    constructor(private subscriptionService: SubscriptionService, private http: Http, private router: Router) { 
     this.credentials = new Credentials('', ''); 
     this.authenticatedUser = new AuthenticatedUser('user', null); 
    } 

    submit() { 
     let formData = { 
      username: this.credentials.name, 
      password: this.credentials.password 
     }; 

     let bodyString = JSON.stringify(formData); 
     let headers = new Headers({'Content-Type': 'application/json'}); 
     let options = new RequestOptions({headers: headers}); 

     this.http.post('/auth', bodyString, options).map(res => res.json()).subscribe(
      data => localStorage.setItem(this.TOKEN_KEY, data.token), 
      error => console.log("Error" + error), 
      () => this.checkUser()); 
      this.loggedIn = true; 
      this.notify.emit(this.loggedIn); 
    } 

    checkUser() { 
     let token = localStorage.getItem(this.TOKEN_KEY); 
     if(token !== null){ 
      console.log('Login successful : token stored'); 
     } else { 
      console.log('No token found in local storage'); 
     } 

     let headers = new Headers(); 
     this.createAuthorizationHeader(headers); 

     this.http.get('/user', {headers: headers}).map(res => res.json()).subscribe(
      data => this.authenticatedUser = data, 
      error => console.log("Error" + error), 
      () => this.assignPriviledge(headers)); 
    } 

    assignPriviledge(headers : any) { 
     this.subscriptionService.connectClientToSocket(headers); 
     this.subscriptionService.loadBoards(headers); 

     // set current user name 
     localStorage.setItem(this.USER_KEY, this.authenticatedUser.username); 
     console.log('Username stored'); 

     setTimeout(() => { 
      this.subscriptionService.waitForMessagesFromSocket(); 
     }, 3000); 

     if(this.authenticatedUser.admin == true){ 
      localStorage.setItem(this.ADMIN_KEY, "admin"); 
      console.log('Current user: ' + this.authenticatedUser.username + ' : ADMIN'); 
     } else { 
      localStorage.setItem(this.ADMIN_KEY, "user"); 
      console.log('Current user: ' + this.authenticatedUser.username + ' : USER'); 
      console.log('Redirecting to my-teams'); 
      this.router.navigate(['my-teams']);//Updated from playerScreen to my-teams 
     } 
    } 

    createAuthorizationHeader(headers: Headers) { 
     let token = localStorage.getItem(this.TOKEN_KEY); 
     if(token){ 
      headers.append('Authorization', token); 
     } else { 
      console.log('No token found!'); 
     } 
    } 

    logout() { 
     let headers = new Headers(); 
     this.createAuthorizationHeader(headers); 

     this.http.get('/userLogout', {headers: headers}).map(res => res.json()).subscribe(
      error => console.log("Error" + error), 
      () => console.log('User logged out')); 

     localStorage.removeItem(this.TOKEN_KEY); 
     localStorage.removeItem(this.ADMIN_KEY); 

     this.authenticatedUser = new AuthenticatedUser('user', null); 
    } 
} 

HTML

<!-- Modal HTML --> 
<div id="myModal" class="modal fade"> 
    <div class="modal-dialog"> 
     <div class="modal-content"> 
      <div class="modal-header"> 
       <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> 
       <h4 class="modal-title">Login to Nimble</h4> 
      </div> 
      <div class="modal-body">    
       <form (ngSubmit)="onSubmit()" #loginForm="ngForm"> 
        <div class="form-group"> 
         <label for="name">Username</label> 
         <input type="text" placeholder = "Enter Your Username" class="form-control" id="name" 
           required 
           [(ngModel)]="credentials.name" name="name" 
           #name="ngModel" > 
         <div [hidden]="name.valid || name.pristine" class="alert alert-danger"> 
          Username is required 
         </div> 
        </div> 
        <div class="form-group" required minlength="4"> 
         <label for="password">Password</label> 
         <input type="password" placeholder = "Enter Your Password" class="form-control" id="password" 
           required 
           [(ngModel)]="credentials.password" name="password" 
           #name="ngModel" > 
         <div [hidden]="name.valid || name.pristine || name. minlenght" class="alert alert-danger"> 
          Password is Required 
         </div> 
        </div> 
       </form>     
      </div> 

      <div class="modal-footer"> 
       <button type="button" class="mdl-button mdl-js-button mdl-button--raised " data-dismiss="modal">Close</button> 
       <button type="button" class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored " (click)="submit(); loginForm.reset()" data-dismiss="modal" routerLink="/home">Login</button> 
      </div> 
     </div> 
    </div> 
</div> 

答えて

0

これはあなたが何であるかである場合、私はわからないんだけど探していますが、似たようなコードを使ってフォームが有効になるまで[送信]ボタンを無効にすることもできますこれに:

  <div class="form-group"> 
       <div class="col-md-4 col-md-offset-2"> 
        <span> 
         <button class="btn btn-primary" 
           type="submit" 
           [disabled]="!loginForm.valid"> 
          Save 
         </button> 
        </span> 
       </div> 
      </div>