How to use pathlocationstrategy in angular 5 to set base href or APP_BASE_HREF?

1.1k views Asked by At

Below is the code snippet:

import { Router } from "@angular/router"; import { HttpClient } from "@angular/common/http"; import { environment } from "../../environments/environment"; import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common';

@Injectable()
export class CommonServicesService {
    PathLocation: Location;
    referralCode: any = localStorage.getItem('referenceCode');

    constructor(
        location: Location,
    ) {
        this.PathLocation = location;
    }

    redirectAfterSuccessfulLogin() {
        if (localStorage.getItem("redirectUrl")) {
            let url = localStorage.getItem("redirectUrl");
            localStorage.removeItem("redirectUrl");
            this.PathLocation.prepareExternalUrl("'/'+this.referralCode"); //is this the correct way?
            console.log(this.PathLocation);
            this.router.navigate([url]);
        } else {
            this.PathLocation.prepareExternalUrl("'/'+this.referralCode");
            console.log(this.PathLocation);
            this.router.navigate(["/"]);
        }
    }
}
1

There are 1 answers

4
Muhammad Shaharyar On

you can do some thing like that :

  1. Create a baseUrl function that takes code as a parameter.
  2. Call that function according to the condition after login,this will gives you the updated URL

like this:

getBaseUrl = function(code){
return `localhost:3000/${code}`
}

now you can use it as :

getBaseURl(1234)

it returns : "localhost:3000/1234"

now you can add further path after this URL.

Example

OR

you can further use same function for both the URL like this :

 getBaseUrl = function(code){

    if(code == 0000) return localhost:3000
    else return `localhost:3000/${code}`

}

now whenever you are calling the function you have to pass 0000 for non-login condition Base Url and 4 digit code to get the after login base URL

getBaseURl(1234) // for login one

getBaseURl(0000) // for non-login one