简体   繁体   English

如何在角度5中使用pathlocationstrategy设置基本href或APP_BASE_HREF?

[英]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"; 从“ @ angular / router”导入{Router}; import { HttpClient } from "@angular/common/http"; 从“ @ angular / common / http”导入{HttpClient}; import { environment } from "../../environments/environment"; 从“ ../../environments/environment”导入{环境}; import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common'; 从'@ angular / common'导入{Location,LocationStrategy,PathLocationStrategy};

@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. 创建一个以代码为参数的baseUrl函数。
  2. Call that function according to the condition after login,this will gives you the updated URL 登录后根据情况调用该函数,这将为您提供更新的URL

like this: 像这样:

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

now you can use it as : 现在您可以将其用作:

getBaseURl(1234)

it returns : "localhost:3000/1234" 它返回: “ localhost:3000/1234”

now you can add further path after this URL. 现在您可以在该URL之后添加其他路径。

例

OR 要么

you can further use same function for both the URL like this : 您可以对两个URL进一步使用相同的功能,如下所示:

 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 现在,无论何时调用该函数,都必须为非登录条件Base Url和4位代码传递0000 ,以获取登录后的基本URL

getBaseURl(1234) // for login one

getBaseURl(0000) // for non-login one

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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