Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

82
Views
Why does angular router url doesn't have the same value as window.location.href

Was working on my website and had to do some request to the api while instantiating a root services.

I wanted to get some data based on the url, so I did the following

@Injectable({
  providedIn: 'root',
})
export class MyService {

  constructor(private _router: Router) {
     this.init() 
  }

  init() {
    console.log('url', this._router.url, window.location.href)
    // this._router.url : `/`
    // window.location.href : `http://localhost:4201/my/url`
    // Here I'll make some get request with the url
  }
}

But I see the the router doesn't have the correct value yet, or at least, not all the time.

Funnily, sometime it does work.

What should I do to be able to get the location without using the window object?

8 months ago · Juan Pablo Isaza
2 answers
Answer question

0

window.location.href defines DOM location, while router.url is based on basehref. Check basehref and RouterModule.forRoot([])

8 months ago · Juan Pablo Isaza Report

0

Basically you use Angular Router to route between pages inside your application, and for every external route you should use window.location/href(html).

As answered here https://stackoverflow.com/a/72514835/12677894

window.location.href defines DOM location, while router.url is based on basehref *

8 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs