Saswat
Saswat

Reputation: 12856

How to redirect in Angular2 on receiving success status?

I don't want to use location.href which actually loads/refreshes and redirects to the url. I want same page loading (don't know if that is the actual term), ie. the page to open without reloading or refreshing the browser.

Here are the routes that are defined in my app.module.ts.

const appRoutes: Routes = [
  { path: 'admin',
    component: AdminComponent,
    children: [
          { path: '', component: LoginComponent},
          { path: 'dashboard', component: DashboardComponent}
    ]
  }
];

Here is the submit function defined in my login.component.ts.

submitPost()
{        
    this._adminLogin.postAdminLogin(this.adminLoginmodel).subscribe(
        data => {
              this.responseStatus = data;
              if(this.responseStatus.status.length > 0 && this.responseStatus.status == 1)
              {
                alert('Login Success');
              }
              else
              {
                alert('Login Error');
              }
            },
        err => {
              console.log(err)
            },
        () => {}
    ); 
    this.status = true;       
}

How can I do this?

EDIT:

Thanks to people for their suggestions in the answer section. However, router.navigate('admin/dashboard') is throwing me an error in the console:

ReferenceError: router is not defined
Stack trace:
LoginComponent.prototype.submitPost/<@webpack-internal:///./src/app/admin/login/login.component.ts:32:17
SafeSubscriber.prototype.__tryOrUnsub@webpack-internal:///./node_modules/rxjs/_esm5/Subscriber.js:245:13
SafeSubscriber.prototype.next@webpack-internal:///./node_modules/rxjs/_esm5/Subscriber.js:192:17

But I have added imported Router in my login.component from before. Here is my total code in login.component.ts:-

import { Component, OnInit, Input } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';

import { fadeInAnimation } from '../../_animations/index';
import { Admin } from '../../_models/admin.model';
import { AdminLoginService } from '../../_admin_service/admin.login';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css'],
  animations: [fadeInAnimation],
  host: { '[@fadeInAnimation]': '' },
  providers: [AdminLoginService]
})

export class LoginComponent implements OnInit {
    loading = false;
    returnUrl: string;
    responseStatus:Object= [];
    status:boolean ;
    //@Input() admin:Admin;

  adminLoginmodel = new Admin('', '', '', 'Emailsss','Passwordsss');    

    constructor(
        private route: ActivatedRoute,
        private router: Router,
        private _adminLogin: AdminLoginService
    ){}

    submitPost()
  {        
      this._adminLogin.postAdminLogin(this.adminLoginmodel).subscribe(
          data => {
                this.responseStatus = data;
                if(this.responseStatus.status == 1)
                {
                  this.router.navigate('admin/dashboard')
                }
                else
                {
                  alert('Login Error');
                }
              },
          err => {
                console.log(err)
              },
          () => {}
      ); 
      this.status = true;       
  }

    ngOnInit() {
    }
}

Why am I getting the error?

Upvotes: 2

Views: 1520

Answers (4)

Simply Ged
Simply Ged

Reputation: 8672

You need to inject the angular router into your component and then call navigate.

    export class MyClass {
      constructor(private router: Router) {}

      submitPost() {        
          this._adminLogin.postAdminLogin(this.adminLoginmodel).subscribe(
            data => {
              this.responseStatus = data;
              if(this.responseStatus.status.length > 0 && this.responseStatus.status === 1)
              {
                  this.router.navigate(['/successUrl']);
              }
              else
              {
                  this.router.navigate(['/errorUrl']);
              }
            },
        err => {
              console.log(err)
            },
        () => {}
    ); 
    this.status = true;       
    }
 }

Upvotes: 3

Anuradha Gunasekara
Anuradha Gunasekara

Reputation: 6983

Hope this helps. You just have to pass a arry to router.navigate method.

  import { Injectable } from '@angular/core';
  import { Router } from '@angular/router';

  @Injectable()
  export class ErrorHandlerService {
      constructor(private router: Router) {}

      public handleError(): void {
          this.router.navigate(['/your-redirect-path']).catch(() => {
               console.log('Navigation Failure');
          });
      }
  }

Upvotes: 2

Orodan
Orodan

Reputation: 1047

You can inject the Router in your component and use it to redirect your user to where you want without having to perform a complete reload of your app like with location.href.

For example, i you have a "success" route to redirect your use in case of success, and otherwise a "fail" route, it would looks like something like that :

constructor (private router: Router) {}

submitPost () {
    this._adminLogin.postAdminLogin(this.adminLoginmodel).subscribe(
       data => {
            // Do your stuff in case of success
            this.router.navigate(['success']);
       },
       err => {
            // Do your stuff in case of failure
            this.router.navigate(['fail']);
       }
}

Be careful, this way your router is accessible thanks to your class, so you have to use :

this.router.navigate

and not

router.navigate

Hope that helps

Upvotes: 1

Dean Marcussen
Dean Marcussen

Reputation: 617

You can use the Angular Router by injecting it into login.component.ts

import { Router } from "@angular/router";

constructor(private router: Router){}

and in your 'Login Success'

this.router.navigate('dashboard');

Upvotes: 0

Related Questions