gpt4 book ai didi

location - Angular2 : unable to navigate to url using location. 去(网址)

转载 作者:太空狗 更新时间:2023-10-29 16:56:26 25 4
gpt4 key购买 nike

我正在尝试使用来自 typescript 函数的 location.go 服务导航到特定的 url。它更改了浏览器中的 url,但 url 的组件未反射(reflect)在屏幕中。它停留在登录(实际)屏幕上 - 例如:

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,它通常用于在浏览器上获取规范化 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 方法,该方法将在创建 时采用 ['routeName'] href 使用 [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 函数时,它会返回所有 Instruction需要在其他组件上导航。这里的 Instruction 表示 ComponentInstruction包含关于路由的所有信息,基本上我们在 @RouteConfig 中注册的内容,将被添加到 RouteRegistry(比如在什么 pathComponent 应该分配给 router-outlet

现在检索到的指令被传递给 navigateByInstruction 方法,该方法负责加载组件并将各种内容提供给组件,如 urlParams & parent & child component instruction,如果他们在那里。

说明(在控制台中)

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.

关于location - Angular2 : unable to navigate to url using location. 去(网址),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35533783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com