简体   繁体   English

有没有办法只从 Angular 8 的 URL 中获取子域?

[英]Is there any way to fetch only Subdomain from URL in Angular 8?

Below is my URL and I want only subdomain ie dnyaneshtechno下面是我的 URL,我只想要子域,即 dnyaneshtechno

Url : https://dnyaneshtechno.sharepoint.com网址: https : //dnyaneshtechno.sharepoint.com

As per above URL I want to fetch only 'dnyaneshtechno' I am using angular 8 for front end so Can someone please help me on this.根据上面的 URL,我只想获取 'dnyaneshtechno' 我使用 angular 8 作为前端,所以有人可以帮我解决这个问题。

You can use split and substr functions or get subdomain from an url您可以使用 split 和 substr 函数或从 url 获取subdomain

Example :示例

Dynamic link :动态链接

let getLink =  window.location.href ; 
console.log(getLink)          // dynamic link 
var  subdomain = getLink.substr(COUNT, 1000).split(".")[0]

Using Split Method :使用拆分方法

var Link = "https://SUBDOMAIN.DOMAIN.com"
var subdomain = Link.substr(COUNT, 1000).split(".")[0]
console.log(subdomain)      //SUBDOMAIN

Or Using get subdomain form link使用获取子域表单链接

const { hostname }  = new URL('https://SUBDOMAIN.DOMAIN.com')
const [subdomain] = hostname.split('.')
console.log(subdomain)    //SUBDOMAIN

i hope i will be helpful fo all !我希望我会对大家有所帮助!

Assuming you want to extract the subdomain from the string, this isn't an Angular problem, but pure JavaScript.假设您想从字符串中提取子域,这不是 Angular 问题,而是纯 JavaScript。 There's the URL constructor that can do this:有可以做到这一点的URL构造函数:

 const { hostname } = new URL('https://dnyaneshtechno.sharepoint.com') const [subdomain] = hostname.split('.') console.log(subdomain)

You can use substr and split functions, ie.您可以使用 substr 和 split 函数,即。

var a = "https://dnyaneshtechno.sharepoint.com"
var subdomain = a.substr(9, 1000).split(".")[0]

For an angular based solution by injecting the DOCUMENT from @angular/platform-browser like this对于通过像这样从@angular/platform-b​​rowser 注入 DOCUMENT 的基于角度的解决方案

import { Injectable, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';

@Injectable()
export class SampleService {

    constructor(@Inject(DOCUMENT) private document: Document) {
    }

    getDomainname() : string{
        return this.document.location.host.split('.')[0];
    }
}

getDomainName() will return the domain of current page. getDomainName() 将返回当前页面的域。

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

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