获取Angular中的当前URL

ndg*_*eek 101 javascript url-routing typescript angular

如何在AngularJS 4中获取当前URL?我在网上搜索了很多,但无法找到解决方案.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Router } from '@angular/Router';

import { AppComponent } from './app.component';
import { TestComponent } from './test/test.component';
import { OtherComponent } from './other/other.component';
import { UnitComponent } from './unit/unit.component';

@NgModule ({
  declarations: [
    AppComponent,
    TestComponent,
    OtherComponent,
    UnitComponent
  ],

  imports: [
    BrowserModule,
    RouterModule.forRoot([
        {
            path: 'test',
            component: TestComponent
        },
        {
            path: 'unit',
            component: UnitComponent
        },
        {
            path: 'other',
            component: OtherComponent
        }
    ]),
  ],

  providers: [],
  bootstrap: [AppComponent]
})

export class AppModule { }
Run Code Online (Sandbox Code Playgroud)

app.component.html

<!-- The content below is only a placeholder and can be replaced -->
<div>
    <h1>Welcome to {{title}}!!</h1>

    <ul>
        <li>
            <a routerLink="/test">Test</a>
        </li>
        <li>
             <a routerLink="/unit">Unit</a>  
        </li>
        <li>
            <a routerLink="/other">Other</a>
        </li>
    </ul>
</div>
<br/>
<router-outlet></router-outlet>
Run Code Online (Sandbox Code Playgroud)

app.component.ts

import { Component} from '@angular/core';

@Component ({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent{
    title = 'Angular JS 4';
    arr = ['abcd','xyz','pqrs'];
}
Run Code Online (Sandbox Code Playgroud)

other.component.ts

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-other',
  templateUrl: './other.component.html',
  styleUrls: ['./other.component.css']
})

export class OtherComponent implements OnInit {

    public href: string = "";
    url: string = "asdf";

    constructor(private router : Router) {}

    ngOnInit() {
        this.href = this.router.url;
        console.log(this.router.url);
    }
}
Run Code Online (Sandbox Code Playgroud)

test.component.ts

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})

export class TestComponent implements OnInit {
    route: string;
    currentURL='';

    constructor() { 
        this.currentURL = window.location.href; 
    }

    ngOnInit() { }
}
Run Code Online (Sandbox Code Playgroud)

现在我点击其他链接后出现控制台问题

ERROR Error: Uncaught (in promise): Error: No provider for Router!
Run Code Online (Sandbox Code Playgroud)

Mac*_*der 178

使用纯JavaScript:

console.log(window.location.href)

使用Angular:

this.router.url

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
    template: 'The href is: {{href}}'
    /*
    Other component settings
    */
})
export class Component {
    public href: string = "";

    constructor(private router: Router) {}

    ngOnInit() {
        this.href = this.router.url;
        console.log(this.router.url);
    }
}
Run Code Online (Sandbox Code Playgroud)

plunkr在这里:https://plnkr.co/edit/0x3pCOKwFjAGRxC4hZMy?p = preview

  • “ window.location.href”返回页面的绝对URL(包括协议和域),而“ this.router.url”返回应用程序内的相对路径...我真的不明白这是公认的答案,因为此解决方案将返回2个完全不同的结果!!!我也不明白怎么可能将链接的问题标记为重复,因为链接的问题正在询问路线网址,而这里的问题是在询问绝对路径 (35认同)
  • 得到错误:属性“路由器”不存在于类型 &lt;component_name&gt;' :( (2认同)
  • 您是否为组件构造函数提供了路由器? (2认同)
  • @MaciejTreder 你提到的这个方法 `this.router.url` 将在页面重新加载时触发。有没有其他方法可以在“Angular 4”中获取路径“URL”而无需重新加载页面? (2认同)

Lal*_*eva 29

您可以使用@ angular/common中提供的位置服务,通过以下代码,您可以获取位置或当前URL

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-top-nav',
  templateUrl: './top-nav.component.html',
  styleUrls: ['./top-nav.component.scss']
})
export class TopNavComponent implements OnInit {

  route: string;

  constructor(location: Location, router: Router) {
    router.events.subscribe((val) => {
      if(location.path() != ''){
        this.route = location.path();
      } else {
        this.route = 'Home'
      }
    });
  }

  ngOnInit() {
  }

}
Run Code Online (Sandbox Code Playgroud)

这里是我复制东西以获取项目位置的参考链接. https://github.com/elliotforbes/angular-2-admin/blob/master/src/app/common/top-nav/top-nav.component.ts


小智 6

其他组件.ts

所以最终正确的解决方案是:

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router'; 

/* 'router' it must be in small case */

    @Component({
      selector: 'app-other',
      templateUrl: './other.component.html',
      styleUrls: ['./other.component.css']
    })

    export class OtherComponent implements OnInit {

        public href: string = "";
        url: string = "asdf";

        constructor(private router : Router) {} // make variable private so that it would be accessible through out the component

        ngOnInit() {
            this.href = this.router.url;
            console.log(this.router.url);
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 您能解释一下为什么这是正确的解决方案吗?我更愿意获得一个“UrlSegment[]”类型的数组,而不是与“Router”一起使用它 (3认同)