是的,对于从一个路由重定向到另一个路由,您不应该使用location.go,它通常用于在浏览器上获取normalized url。
Location docs 已在下面的注释中严格提及。
注意:最好使用Router服务来触发路由变化。采用
仅当您需要与规范化 URL 交互或创建规范化 URL 时才定位
在路由之外。
您应该使用Router API 的navigate 方法,当您使用[routerLink] 指令创建href 时,该方法将采用['routeName']。
如果您只想通过 URL 进行重定向,那么您可以使用 navigateByUrl,它将 URL 作为字符串,例如 router.navigateByUrl(url)
import {
ROUTER_DIRECTIVES,
RouteConfig,
ROUTER_PROVIDERS,
Location, //note: in newer angular2 versions Location has been moved from router to common package
Router
} from 'angular2/router';
constructor(location: Location,
public _userdetails: userdetails,
public _router: Router){
this.location = location;
}
login(){
if (this.username && this.password){
this._userdetails.username = this.username;
//I assumed your `/home` route name is `Home`
this._router.navigate(['Home']); //this will navigate to Home state.
//below way is to navigate by URL
//this.router.navigateByUrl('/home')
}
else{
console.log('Cannot be blank');
}
}
更新
在进一步的研究中,我发现,当你调用navigate时,基本上它确实接受数组内部的routeName,如果有参数,那么应该像['routeName', {id: 1, name: 'Test'}]一样通过它。
下面是navigateRouter的API函数。
Router.prototype.navigate = function(linkParams) {
var instruction = this.generate(linkParams); //get instruction by look up RouteRegistry
return this.navigateByInstruction(instruction, false);
};
当linkParams 传递给generate 函数时,它确实返回了导航其他组件所需的所有Instruction。这里Instruction 表示ComponentInstruction 包含有关路由的所有信息,基本上我们在@RouteConfig 中注册的内容将被添加到RouteRegistry(就像path 应该分配给@ 的内容一样) 987654349@)。
现在检索到的指令被传递给 navigateByInstruction 方法,该方法负责加载组件,并将使各种东西可用于组件,如 urlParams 和父子组件指令(如果它们存在)。
说明(在控制台中)
auxInstruction: Object //<- parent instructions
child: null //<- child instructions
component: ComponentInstruction //<-current component object
specificity: 10000
urlParams: Array[0] <-- parameter passed for the route
urlPath: "about" //<-- current url path
注意:整个答案基于较旧的路由器版本,当时 Angular 2 处于测试版。