2016-12-05 2 views
1

У меня возникла проблема с выполнением перенаправления после отправки формы для входа в систему на угловом 2. Приложение выполняет полную перезагрузку при перенаправлении на панель управления. Я проверил несколько сообщений о переполнении стека & других блогов, без везения. This - самый близкий; Однако ответа на поток нет. См. Мой код ниже.Угловая 2 Полная перезагрузка на router.navigate

После того, как я нажимаю логин, страница загружается, а затем перезагружается снова. URL-адрес также изменяется, чтобы поместить строку запроса в URL-адрес, который, как я подозреваю, вызывает проблему. Как я могу исправить эту проблему? Я подозреваю, что это связано с тем, как моя форма настроена.

auth.component.ts

import { Component, OnInit, ViewChild } from '@angular/core'; 
import { NgForm, FormBuilder, Validators } from '@angular/forms'; 
import { Router } from '@angular/router'; 

import { User } from '../shared/user'; 
declare var Materialize:any; 

import { AuthService } from '../shared/services/auth.service'; 

@Component({ 
    moduleId: module.id, 
    selector: 'logon', 
    templateUrl: 'auth.component.html', 
}) 
export class AuthComponent implements OnInit { 

    currentUser = new User(null, '', '', '', '', 'vistor'); 
    submitted = false; 
    authForm: NgForm; 
    @ViewChild('authForm') currentForm: NgForm; 

    constructor(
    private router: Router, 
    public authService: AuthService 
) { } 

    ngOnInit(): void { 
    } 

    onSubmit() { 
    this.submitted = true; 
    this.authService.login(this.currentUser).then(response => { 
     if (response) { 
     this.goToDashboard(); 
     } else { 
     var toastContent = '<span><b>Invalid email or password!</b></span>'; 
     Materialize.toast(toastContent, 5000, 'red'); 
     } 
    }); 
    } 

    goToDashboard() { 
    this.router.navigate(['dashboard']); 
    } 
} 

auth.component.html

<div class="container"> 
    <div class="card"> 
    <div class="card-content"> 
     <span class="card-title">Logon</span> 
     <form materialize #authForm="ngForm" class="col s12"> 

     <div class="input-field col s12"> 
      <input required class="validate" id="email" type="email" name="email" [(ngModel)]="currentUser.email" #email="ngModel" validate="email"> 
      <label for="email" data-error="Invalid Email">Email</label> 
     </div> 

     <div class="input-field col s12"> 
      <input required class="validate" id="password" type="password" name="password" [(ngModel)]="currentUser.password" #password="ngModel" validate="password"> 
      <label for="password" data-error="Invalid Password">Password</label> 
     </div> 

     <div class="card-action"> 
      <button [disabled]="!authForm.form.valid" (click)="onSubmit()" class="btn orange darken-1 waves-effect waves-light" type="submit">Log In 
      <i class="material-icons right">send</i> 
      </button> 
     </div> 
     </form> 
    </div> 
    </div> 
</div> 

Угловые 2 Маршруты

const routes: Routes = [ 
    { path: '', redirectTo: '/auth', pathMatch: 'full' }, 
    { path: 'dashboard', component: DashboardComponent }, 
    { path: 'spelling', component: SpellingComponent }, 
    { path: 'definition', component: DefinitionComponent }, 
    { path: 'auth', component: AuthComponent }, 
    { path: '**', redirectTo: '/dashboard', pathMatch: 'full' } 
]; 

ответ

0

Угловое 2 необходим порядок в путях, чтобы показать правильную маршрутизацию , Я думаю, что решение связано с порядком путей. Например, вы можете попробовать это:

const routes: Routes = [ 
{ path: '', redirectTo: '/auth', pathMatch: 'full' }, 
{ path: 'auth', component: AuthComponent }, 
{ path: 'dashboard', component: DashboardComponent }, 
{ path: 'spelling', component: SpellingComponent }, 
{ path: 'definition', component: DefinitionComponent }, 
{ path: '**', redirectTo: '/dashboard' } 
]; 

и

goToDashboard() { 
this.router.navigate(['dashboard/']); 
} 
+0

я попытался эти изменения, и это не изменило выпуск строки запроса, что у меня после страницы AUTH. – technogeek1995

0

Не используйте тип, как представить в приложениях Угловая одной странице. Причиной может быть

<button [disabled]="!authForm.form.valid" (click)="onSubmit()" class="btn orange darken-1 waves-effect waves-light" type="submit">Log In 
     <i class="material-icons right">send</i> 
</button> 

Попробуйте использовать

<button [disabled]="!authForm.form.valid" (click)="onSubmit()" class="btn orange darken-1 waves-effect waves-light" type="button">Log In 
     <i class="material-icons right">send</i> 
     </button> 
Смежные вопросы