【问题标题】:location.go() is not redirecting the user in angular 2location.go() 没有以角度 2 重定向用户
【发布时间】:2017-08-09 01:51:32
【问题描述】:

我正在进行登录检查。一旦成功,我想将用户重定向到同一应用程序中的另一个页面。我有以下代码可以做到这一点。

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)
      });;
}

}

但问题是,浏览器中的 URL 更改为 http://localhost:3000/report。但是当页面没有加载时。当我点击重新加载时,就会显示新页面。

这段代码有什么问题? location.go() 不会加载 URL。

【问题讨论】:

标签: angular typescript angular2-routing


【解决方案1】:

如果您使用 Angular 路由器,则使用位于 angular/router 命名空间的路由器类。 看看这个 Angular Router Navigation example。 我认为这将有助于解决您的问题。 Location class 旨在与 URL 交互,但不是在应用程序路由中导航(就像在 Angular 1 中所做的那样)。

引用那篇关于位置类的文章:"

注意:最好使用Router服务来触发路由变化。仅当您需要与路由之外的规范化 URL 交互或创建规范化 URL 时才使用位置。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-03
    • 2020-05-11
    • 2014-06-26
    • 1970-01-01
    相关资源
    最近更新 更多