【发布时间】: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 的回答应该对您有所帮助