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

Angular2: unable to navigate to url using location.go(url)

我正在尝试使用来自 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');
    }
}

是否缺少编译方法或刷新方法?

是的,为了从一条路线重定向到另一条路线,您不应该使用 location.go,它通常用于在浏览器上获取 normalized url

Location docs 已经严格提到了下面的注释。

Note: it's better to use Router service to trigger route changes. Use Location only if you need to interact with or create normalized URLs outside of routing.

您应该使用 Router API 的 navigate 方法,在使用 [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');
    }
}

更新

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

下面是Routernavigate函数的API。

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

linkParams 传递给 generate 函数时,它会 return 输出所有 Instruction's required to navigate on other compoent. Here Instruction means ComponentInstruction,其中包含有关路由的所有信息,基本上是我们在其中注册的所有信息@RouteConfig,将被添加到 RouteRegistry(就像 Component 应该分配给 router-outletpath)。

现在检索到的指令被传递给 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

Note: Whole answer is based on older router version, when Angular 2 was in beta release.