Angular2:无法使用location.go(url)导航到url

Gar*_*ary 17 location angular2-routing angular

我试图使用typescript函数中的location.go服务导航到特定的URL.它会更改浏览器中的URL,但URL的组件不会反映在屏幕中.它保留在登录(实际)屏幕上 - 例如:

constructor(location: Location, public _userdetails: userdetails){
    this.location = location;
}
login(){
    if (this.username && this.password){
        this._userdetails.username = this.username;
        this.location.go('/home');
    }
    else{
        console.log('Cannot be blank');
    }
}
Run Code Online (Sandbox Code Playgroud)

我缺少一个编译方法或刷新方法吗?

Pan*_*kar 20

是的,对于从一个路由重定向到另一个路由你不应该使用location.go它,它通常用于normalized url浏览器.

位置文档严格提到下面的注释.

注意:最好使用路由器服务来触发路由更改.仅当您需要在路由之外进行交互或创建规范化URL时才使用位置.

相反,您应该使用RouterAPI的navigate方法,这将['routeName']在创建hrefusing [routerLink]指令时使用它.

如果您只想通过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');
    }
}
Run Code Online (Sandbox Code Playgroud)

更新

在进一步的研究中,我发现,当你调用时navigate,基本上它确实接受routeName内部数组,如果参数在那里,那么应该像它一样传递它['routeName', {id: 1, name: 'Test'}].

下面是API的navigate功能Router.

Router.prototype.navigate = function(linkParams) {
  var instruction = this.generate(linkParams); //get instruction by look up RouteRegistry
  return this.navigateByInstruction(instruction, false);
};
Run Code Online (Sandbox Code Playgroud)

linkParams传递给generate函数时,它确实返回了在其他组件上导航所需的所有指令.这里InstructionComponentInstruction的哪些有关于路由的所有信息,基本上什么都我们的内部寄存器@RouteConfig,将添加到RouteRegistry(像什么pathComponent应该分配给给router-outlet).

现在检索到的指令被传递给navigateByInstruction方法,该方法负责加载组件,并且urlParams如果它们在那里,将使各种组件可用于&parent&child组件指令.

说明(在控制台中)

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
Run Code Online (Sandbox Code Playgroud)

注意:当Angular 2处于测试版时,整个答案基于较旧的路由器版本.