正确使用角度的位置类

时间:2018-01-12 01:43:45

标签: angular

我在http://myexaple.com/subFolder1

我希望this.location.go将顶部的网址从http://myexaple.com/subFolder1更改为http://myexaple.com/subFolder2

就这么简单。

所以,我去了

this.location.go(' / subFolder2&#39); //无论如何你还能做什么?!

但结果是 http://myexaple.com/subFolder1/subFolder2

https://angular.io/api/common/Location的文档感觉我正在做的事情似乎是正确的。

我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

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

相反,您应该使用Router API的navigate方法,在使用['routeName']指令创建href时使用[routerLink]

如果您只想通过网址重定向,那么您可以使用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');
    }
}