gpt4 book ai didi

javascript - 在 Angular 中获取当前 url

转载 作者:IT王子 更新时间:2023-10-29 02:45:50 27 4
gpt4 key购买 nike

<分区>

如何获取 Angular 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 { }

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

现在我在点击other 链接后​​遇到控制台问题

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

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com