【问题标题】:Get current url in Angular [duplicate]在Angular中获取当前网址[重复]
【发布时间】:2017-12-24 09:29:10
【问题描述】:

如何在 Angular 4 中获取当前网址?我在网上搜索了很多,但找不到解决方案。

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 { }

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>

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'];
}

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

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() { }
}

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

ERROR Error: Uncaught (in promise): Error: No provider for Router!

【问题讨论】:

  • 哪个网址???浏览器网址,请添加一些您尝试过的代码,以便更详细地了解您的问题
  • @MaciejTreder : link 已经通过此链接,但没有成功。
  • 你可以使用 import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) 导出类 AppComponent { title = 'app';当前网址='';构造函数() { this.currentURL=window.location.href; } }
  • 您在import { RouterModule, Router } from '@angular/Router'; 中有错字,应该是@angular/router
  • 我试图在 plunkr 中重现您的问题。一切正常:plnkr.co/edit/0x3pCOKwFjAGRxC4hZMy?p=preview

标签: frontend


【解决方案1】:

使用纯 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);
    }
}

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

【讨论】:

  • 出现错误: 类型上不存在属性“路由器”:(
  • 你给组件构造器提供路由了吗?
  • 您是否导入了RouterModule?看看这个 plunker:plnkr.co/edit/bmT3HSXdTmgAguiIL6zE?p=preview
  • 你检查 plunker 了吗?它对你有用吗?
  • window.location.href 正在返回页面的绝对 URL(包括协议和域),而 this.router.url 正在返回应用程序内部的相对路径......我真的不明白怎么可能这是公认的答案,因为此解决方案返回 2 个完全不同的结果!!!我也不明白怎么可能被标记为重复,因为链接的问题要求路由 url 而这里的问题是要求绝对路径
【解决方案2】:

您可以使用@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() {
  }

}

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

【讨论】:

  • ActivatedRoute等所有这些技巧都简单
  • 这个答案会在当前 url 改变时更新,其他的不会
  • 您可以使用 first() 运算符发出第一个事件:router.events.pipe(first()).subscribe((val) =&gt; {...});
  • 正是我需要的。谢谢。
  • 唯一担心的是,当我 console.log 它运行多次。
【解决方案3】:

other.component.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);
        }
    }

【讨论】:

  • 您能解释一下为什么这是正确的解决方案吗?我宁愿获得UrlSegment[] 类型的数组,而不是使用Router
  • @ndgeek 最好将public href: string = "" 替换为get 属性。这样就无需在ngOnInit 中分配值,同时还拥有始终最新的路由器 URL。因此:get href(); string { return this.router.url; }。也没有必要设置它public,因为这是默认设置。
猜你喜欢
  • 2012-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-15
  • 1970-01-01
  • 2012-08-26
相关资源
最近更新 更多