【问题标题】:How do I get URL in angular?如何以角度获取 URL?
【发布时间】:2019-06-13 13:48:39
【问题描述】:

我需要根据 url 将我的汉堡包按钮设置为汉堡包或十字。所以我需要获取我当前的网址。

这就是我现在拥有的:

当我单击汉堡包按钮时,视图切换到设置视图(如预期的那样)并且我的 url 更改为“http://localhost:4200/settings”,但是当我尝试获取 url 时它只返回一个 '/'。

header.component.ts

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

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

public href: string = "";

  constructor(private router: Router) { }


  ngOnInit() {
    this.href = this.router.url;
        console.log(this.router.url);
  }

}

##########EDIT#############

Alvaro 的回答有效,但它刷新了页面(我以前没有考虑过,抱歉)。我只想让它改变视图而不是刷新页面。

我现在拥有的是:

header.component.html

<div class="hamburguer">
        <a (click)="getUrl(); showFirst=!showFirst;">
            <img *ngIf="!showFirst" src="assets/images/hamburguer.png" id="hamburguer">
            <img *ngIf="showFirst" src="assets/images/cross.png" id="hamburguer">
        </a>
</div>

header.component.ts

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

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  constructor(private router: Router, private _location: Location) { }

  getUrl(){

    if(window.location.pathname != "/settings"){
        window.location.pathname = "/settings";
    }else{
        this._location.back();
    }

  }

  ngOnInit() {
  }

}

这是一个视频:https://vimeo.com/342053009

【问题讨论】:

  • 您是否尝试在构造函数中添加router.url 并记录它?
  • 这是因为您仅在 ngOnInit 上分配 url,除非您重构 HeaderComponent,否则它不会改变。您需要订阅路线更改。 @Alvaro 的回答应该对您有所帮助

标签: angular url routes


【解决方案1】:

你可以用纯 javascript 得到它: window.location.pathname

或者使用ActivatedRoute 并订阅它的URL 事件。这是一个例子:

constructor(public activatedRoute: ActivatedRoute) {

   activatedRoute.url.subscribe(url => {
       // do what you need here
   }
}

要导入ActivatedRoute,请添加以下行:

import { ActivatedRoute } from '@angular/router';

希望对你有帮助!

【讨论】:

  • 泰!我使用了window.loaction.pahtname,它奏效了。唯一的问题是它刷新了页面(我以前没有考虑过这个,抱歉),我只是希望它改变视图。我编辑了我的帖子,所以你可以看到我现在有什么
  • 要更改视图,您尝试过this.router.navigate(['../new-package'], {relativeTo:this.activatedRoute}); 吗?
【解决方案2】:

试试这个:

 import { Location } from "@angular/common";

 url: string;
 constructor(location: Location) {
    this.url = location.path();
 }

【讨论】:

    猜你喜欢
    • 2018-11-25
    • 2020-09-11
    • 2018-04-15
    • 2022-12-21
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 2021-07-05
    相关资源
    最近更新 更多