简体   繁体   中英

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

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(["/"]);
        }
    }
}

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.

例

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM