2017-03-17 27 views
1

我正在進行登錄檢查。一旦成功,我想將用戶重定向到同一應用程序中的另一個頁面。我有下面的代碼來做到這一點。location.go()沒有重定向角2中的用戶

import { Component } from '@angular/core'; 
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; 
import { DataService } from '../services/data.service'; 
import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common'; 

@Component({ 
    selector: 'app-login', 
    templateUrl: './login.component.html', 
    providers: [Location, {provide: LocationStrategy, useClass: PathLocationStrategy}], 
    styleUrls: ['./login.component.css'], 

}) 
export class LoginComponent { 

static location:Location; 

    constructor(private formBuilder: FormBuilder, 
       private dataService: DataService,location: Location) { 
       LoginComponent.location = location; 

     this.loginForm = this.formBuilder.group({ 
     username: this.username, 
     password: this.password 
    }); 
    } 

    loginForm : FormGroup; 
    username = new FormControl('', Validators.required); 
    password = new FormControl('', Validators.required); 

Login(){ 

    this.dataService.doLogin(this.loginForm.value.username,this.loginForm.value.password).subscribe(function(res){ 
     console.log(LoginComponent.location) 
     LoginComponent.location.go('/report'); 
    },function(err){ 
     console.log("Err",err) 
     });; 
} 

}

但問題是,在URL瀏覽器改爲http://localhost:3000/report。但是當頁面沒有加載時。當我點擊重新加載時,新頁面正在顯示。

這段代碼有什麼問題? location.go()將不會加載該網址。

+0

我認爲你應該使用'router'作爲重定向,你是否使用'routing'? –

+0

是的,路由器爲我工作,我引用了http://stackoverflow.com/questions/33571605/angular-2-how -to-導航到另一個路由 - 使用 - 這個路由器,家長導航 –

回答

2

如果使用角度路由器,則使用位於角度/路由器名稱空間的路由器類。 看看這個 Angular Router Navigation example。 我認爲這將有助於解決您的問題。 Location class旨在與URL進行交互,但不能在應用程序路徑中導航(如在角1中所做的那樣)。從文章關於地點類

引用:」

注意:最好是使用路由器服務來觸發路由變化只有當你需要進行交互或路由之外創建規範化的網址,使用位置