typescript location.go() 不会以角度 2 重定向用户
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42858644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
location.go() is not redirecting the user in angular 2
提问by Santosh Hegde
I'm making login check. Once that is the success, I want to redirect the user to another page in the same application. I have below code to do that.
我正在做登录检查。一旦成功,我想将用户重定向到同一应用程序中的另一个页面。我有下面的代码来做到这一点。
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { DataService } from '../services/data.service';
import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
providers: [Location, {provide: LocationStrategy, useClass: PathLocationStrategy}],
styleUrls: ['./login.component.css'],
})
export class LoginComponent {
static location:Location;
constructor(private formBuilder: FormBuilder,
private dataService: DataService,location: Location) {
LoginComponent.location = location;
this.loginForm = this.formBuilder.group({
username: this.username,
password: this.password
});
}
loginForm : FormGroup;
username = new FormControl('', Validators.required);
password = new FormControl('', Validators.required);
Login(){
this.dataService.doLogin(this.loginForm.value.username,this.loginForm.value.password).subscribe(function(res){
console.log(LoginComponent.location)
LoginComponent.location.go('/report');
},function(err){
console.log("Err",err)
});;
}
}
}
But the issue is, URL in browser changed to http://localhost:3000/report. But when the page is not loading. When I hit reload, then the new page is getting displayed.
但问题是,浏览器中的 URL 更改为http://localhost:3000/report。但是当页面没有加载时。当我点击重新加载时,就会显示新页面。
What is wrong in this code? location.go()
won't load the URL.
这段代码有什么问题?location.go()
不会加载 URL。
回答by Imants Volkovs
If you use angular router, then use Router class which is located at angular/router namespace. Take a look at this Angular Router Navigation example. I think that will help to solve your problem. Location classis meant to interact with URL, but not navigate in application routes (as it did in angular 1).
如果您使用 angular 路由器,则使用位于 angular/router 命名空间的 Router 类。看看这个 Angular Router Navigation 示例。我认为这将有助于解决您的问题。 Location 类旨在与 URL 交互,但不会在应用程序路由中导航(就像它在 angular 1 中所做的那样)。
Quote from that article about Location class:"
引用那篇关于 Location 类的文章:”
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服务来触发路由变化。仅当您需要在路由之外与规范化 URL 交互或创建规范化 URL 时才使用 Location。