title: How to redirect to login page, if the process is not completed using angular2
body: <p>I have a Popup, that is used for device verification. 
  So, once i click on login button after giving proper credentials, the popup opens if it is not trusted device, so i need to provide information then after successful validation, it redirects to home page.</p>
  
  <p>My problem is, i clicked on login, so credentials needed for login is provided, and popup opens if its not trusted device, and if i refresh the page in middle of process, then it is redirecting to home page.</p>
  
  <p>Can anyone help me how to solve this issue.</p>
  
  <p>TS:</p>
  
  <pre><code>login(value: any) {
      let userName = value.email.trim();
      let passWord = value.password.trim();
      let password = Md5.hashStr(passWord)
      let params = { username: userName, password: password }
      this.authService.doLogin(params)
        .subscribe((data: any) =&gt; {
          else if (data.Body.Data.token &amp;&amp; data.Body.Data.id != -2) {
            localStorage.setItem("userId_ls", data.Body.Data.userID)
            localStorage.setItem('accountId_ls', data.Body.Data.accountID)
            if (Cookie.get("DeviceUID") == null || this.DeviceUID == 'undefined') {
              this.isUserDevice = true;
  
            }
            else if (this.DeviceUID != null &amp;&amp; this.DeviceUID != undefined &amp;&amp; this.userDId != null) {
              let otpObj = { UserId: this.userDId, otp: "", Guid: this.DeviceUID, savedevice: "" }
              this._userService.confirmDevice(otpObj).subscribe(resp =&gt; {
                  if(resp.message == "Invalid device.") {
  
                    Cookie.delete('DeviceUID');
                    this.router.navigate(['/login']);
                    window.location.reload();
  
                  } else {
                  this.router.navigate(['/home']); }
              })
            }
          }
          else {
            console.log(data.message);
          }
        })
  
    }
  </code></pre>
  
  <p>Routing.ts:</p>
  
  <pre><code>import { NgModule } from '@angular/core';
  import { RouterModule, Routes } from '@angular/router';
  import { CanActivatedAuthGuard } from './core/security-guard/auth.guard';
  
  let routes: Routes = [
    { path: '', redirectTo: '/login', pathMatch: 'full' },
    { path: '', loadChildren: './home/home.module#HomeModule' },
    { path: 'login', loadChildren: './login/login.module#LoginModule' },
    // { path: '**', loadChildren: './login/login.module#LoginModule' },
    { path: 'register', loadChildren: './register/register.module#RegisterModule' },
    { path: 'accountActivation/:userId/:activationCode', loadChildren: './activation/activation.module#ActivationModule' },
  ]
  
  @NgModule({
    imports: [
      RouterModule.forRoot(routes, { useHash: true, enableTracing: false }
      )
    ],
    exports: [RouterModule]
  })
  export class AppRoutingModule { }
  </code></pre>
  
  <p>POPUP HTML:</p>
  
  <pre><code> &lt;p-dialog header="New Device Verification" [(visible)]="isUserDevice" [responsive]="true" showEffect="fade" [modal]="true"
      [width]="400"&gt;
      &lt;div class="form-group row g-mb-25"&gt;
        &lt;div class="col-sm-9 clear-fix"&gt;
          &lt;label class="col-sm-8 col-form-label g-color-gray-dark-v2 g-font-weight-700 g-mb-10"&gt;Choose OTP type
          &lt;/label&gt;
          &lt;div class="col-sm-9 clear-fix" *ngFor="let oType of otpTypes"&gt;
            &lt;label class="form-check-inline u-check g-pl-25"&gt;
              &lt;input type="radio" name="otpType" [value]="oType.otpType" (click)="chooseOtpType(oType)"&gt; {{oType.otpType}}
            &lt;/label&gt;
          &lt;/div&gt;
          &lt;div&gt;
            &lt;div *ngIf="isConfirmEmailOtp"&gt;
              &lt;input class="form-control col-lg-12" type="email" [(ngModel)]="enterEmail" name="myEmail" #myEmail="ngModel" email pattern="[a-zA-Z0-9.-_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}" (input)="submitButton &amp;&amp;submitButton.disabled = false"
                #emailOTP&gt;
                &lt;button (click)="generateEmailOtp(enterSms,enterEmail); submitButton.disabled = true;" class="btn pull-right otp"  #submitButton [disabled] = "enterEmail === ''&amp;&amp; enterSms === ''" &gt;Send OTP&lt;/button&gt;
              &lt;div *ngIf="myEmail.errors &amp;&amp; (myEmail.dirty || myEmail.touched)"&gt;
                &lt;br&gt;
                &lt;div [hidden]="!myEmail.errors" class="error"&gt;
                  Invalid Email.
                &lt;/div&gt;
              &lt;/div&gt;
            &lt;/div&gt;
            &lt;div *ngIf="isSms"&gt;
              &lt;input class="form-control col-lg-12" type="number" [(ngModel)]="enterSms" #smsOTP (input)="submitButton &amp;&amp; submitButton.disabled = false"&gt;
              &lt;button (click)="generateEmailOtp(enterSms,enterEmail); submitButton.disabled = true;" class="btn pull-right otp"  #submitButton [disabled] = "enterEmail === ''&amp;&amp; enterSms === ''" &gt;Send OTP&lt;/button&gt;
            &lt;/div&gt;
          &lt;/div&gt;
        &lt;/div&gt;
          &lt;div class="col-lg-12 row g-mb-10" *ngIf="isConfirmOtp"&gt;
            &lt;label class="col-sm-4 col-form-label g-color-gray-dark-v2 g-font-weight-700 text-sm-left g-mb-10 nopadd"&gt;Verify OTP:
              &lt;span class="required"&gt;*&lt;/span&gt;
            &lt;/label&gt;
            &lt;div class="col-sm-8"&gt;
              &lt;div class="input-group g-brd-primary--focus"&gt;
                &lt;input class="verifyPin" type="text" placeholder="Pin" [(ngModel)] = "otp"&gt;
              &lt;/div&gt;
            &lt;/div&gt;
          &lt;/div&gt; 
      &lt;/div&gt;
      &lt;!-- End Login Verification --&gt;
      &lt;p-footer&gt;
        &lt;div class="col-sm-9 clear-fix saveDevice"&gt;
          &lt;label class="form-check-inline u-check g-pl-25"&gt;
            &lt;input class="g-hidden-xs-up g-pos-abs g-top-0 g-left-0" type="checkbox" [(ngModel)] = "checkboxSave"&gt;
            &lt;div class="u-check-icon-checkbox-v4 g-absolute-centered--y g-left-0"&gt;
              &lt;i class="fa" data-check-icon=""&gt;&lt;/i&gt;
            &lt;/div&gt;
            Save this device
          &lt;/label&gt;
        &lt;/div&gt;
        &lt;div class="ui-dialog-buttonpane ui-helper-clearfix popup"&gt;
          &lt;button type="button" pButton icon="fa-check" label="Save" class="btn u-btn-darkgray g-py-12 g-px-25 g-mr-10" (click)="cancelDevice()"&gt;Cancel&lt;/button&gt;
          &lt;button type="button" pButton icon="fa-check" label="Save" class="btn u-btn-primary g-py-12 g-px-25" (click)="saveDeviceInfo(enterEmail, enterSms, otp,checkboxSave)" [disabled]="!otp"&gt;Ok&lt;/button&gt;
        &lt;/div&gt;
      &lt;/p-footer&gt;
    &lt;/p-dialog&gt;
  </code></pre>
  
  <p>TS:</p>
  
  <pre><code>saveDeviceInfo(enterEmail, enterSms, otp, checkboxSave) {
      var check = checkboxSave;
      var uID = localStorage.getItem('userId_ls');
      if (this.enterEmail != null &amp;&amp; this.enterEmail != "") {
        let otpObj = { userId: uID, otp: otp }
        this._userService.confirmOtpEmail(otpObj).subscribe(resp =&gt; {
          if (resp.Body.Data == "OTP verified successfully") {
            let otpObj = { UserId: uID, otp: otp, Guid: "", savedevice: check, DeviceName: "webBrowser" }
            if(!this.DeviceUID &amp;&amp; this.otp || checkboxSave == true) {
            this._userService.confirmDevice(otpObj).subscribe(resp =&gt; {
              if (resp) {
                Cookie.set('DeviceUID', resp.Guid);
                this.router.navigate(['/home']);
              }
            })
           }
          }
          else if (resp.Body.Data == "OTP is not valid.Please check the OTP") {
            this.enterEmail = "";
            this.enterSms = "";
            this.otp = "";
            this.msgs = [{ severity: 'error', summary: 'Error Message', detail: 'OTP is not valid.Please check the OTP' }];
            this.isUserDevice = false;
            this.isSms = false;
            this.isConfirmEmailOtp = false;
            this.isConfirmOtp = false;
            Cookie.delete('token');
            Cookie.delete('userType');
            Cookie.delete('userID');
            Cookie.delete('profilePic');
            Cookie.delete('Id');
            this.router.navigate(['/login']);
            window.location.reload();
          }
        })
      }
  
      if (this.enterSms != null &amp;&amp; this.enterSms != "") {
        let otpObj = { userId: uID, otp: otp, isRequiredToken: this.isRequiredToken }
        this._userService.confirmOtpSMS(otpObj).subscribe(resp =&gt; {
          if (resp.Body.Data == "OTP verified successfully") {
            let otpObj = { UserId: uID, otp: otp, Guid: "", savedevice: check, DeviceName: "webBrowser" }
            if(!this.DeviceUID &amp;&amp; this.otp || checkboxSave == true) {
            this._userService.confirmDevice(otpObj).subscribe(resp =&gt; {
              if (resp) {
                Cookie.set('DeviceUID', resp.Guid);
                this.router.navigate(['/home']);
              }
            })
          }
          } else if (resp.Header.Message == "User Does Not Exist For This OTP") {
            this.enterEmail = "";
            this.enterSms = "";
            this.otp = "";
            this.msgs = [{ severity: 'error', summary: 'Error Message', detail: 'User Does Not Exist For This OTP' }];
            this.isUserDevice = false;
            this.isSms = false;
            this.isConfirmEmailOtp = false;
            this.isConfirmOtp = false;
            Cookie.delete('token');
            Cookie.delete('userType');
            Cookie.delete('userID');
            Cookie.delete('profilePic');
            Cookie.delete('Id');
            this.router.navigate(['/login']);
            window.location.reload();
          }
        })
      }
    }
  </code></pre>
  
  <p>Here that popup function is coming after success of login, Please help.</p>