如何在接收成功状态时重定向Angular2?

时间:2018-04-04 11:47:03

标签: angular angular2-routing

我不想使用实际加载/刷新的location.href并重定向到网址。我想要同样的页面加载(不知道这是否是实际的术语),即。打开的页面,无需重新加载或刷新浏览器。

以下是 app.module.ts 中定义的路线。

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

这是我的 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;       
}

我该怎么做?

编辑:

感谢人们在答案部分提出建议。但是,router.navigate('admin/dashboard')在控制台中给我一个错误:

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

但是我之前在login.component中添加了导入的Router。这是我在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() {
    }
}

为什么我收到错误?

4 个答案:

答案 0 :(得分:1)

您可以在组件中注入Router并使用它将用户重定向到您想要的位置,而无需像使用location.href那样完全重新加载您的应用。

例如,我有一个“成功”路线来重定向您的使用以防成功,否则一个“失败”路线,它看起来像这样:

-v

小心,这样你的路由器可以通过你的课程访问,所以你必须使用:

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']);
       }
}

而不是

this.router.navigate

希望有所帮助

答案 1 :(得分:1)

您需要将角度router注入您的组件,然后调用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;       
    }
 }

答案 2 :(得分:1)

希望这会有所帮助。你只需要将arry传递给router.navigate方法。

  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');
          });
      }
  }

答案 3 :(得分:0)

您可以通过将Angular路由器注入login.component.ts

来使用它
import { Router } from "@angular/router";

constructor(private router: Router){}

并在“登录成功”

this.router.navigate('dashboard');