Home > Mobile >  Why does angular router url doesn't have the same value as window.location.href
Why does angular router url doesn't have the same value as window.location.href

Time:06-06

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?

CodePudding user response:

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

CodePudding user response:

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 *

CodePudding user response:

constractor(private route:Router){
  route.events.subscribe(res=>{
   if(res instanceof NavigationStart)
     console.log(res.url)
  })
}
  • Related