Récupère l'url actuelle dans Angular [dupliquer]

Cette question a déjà une réponse ici:

Comment puis-je obtenir l'url actuelle dans AngularJS 4? J'ai beaucoup cherché sur le web, mais incapable de trouver solution.

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

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

En ce moment, je reçois un problème de console après avoir cliqué sur other link

ERROR Error: Uncaught (in promise): Error: No provider for Router!
48
demandé sur Maciej Treder 2017-07-19 11:26:55

3 réponses

Avec JavaScript pur:

console.log(window.location.href)

En Utilisant Angulaire:

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

Le plunkr est ici: https://plnkr.co/edit/0x3pCOKwFjAGRxC4hZMy?p=preview

88
répondu Maciej Treder 2017-07-19 14:49:12

Vous pouvez utiliser le service de localisation disponible dans @ angular / common et via ce code ci-dessous, vous pouvez obtenir l'emplacement ou L'URL actuelle

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

}

Voici le lien de référence d'où j'ai copié la chose pour obtenir l'emplacement de mon projet. https://github.com/elliotforbes/angular-2-admin/blob/master/src/app/common/top-nav/top-nav.component.ts

14
répondu Lalit Sachdeva 2017-07-19 08:33:41

Autres.composant.ts

Donc la solution correcte finale est:

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);
        }
    }
1
répondu Nilam Dhok 2017-07-19 14:11:24