Angular 7 : 如何获取当前页面的完整URL

Angular 7 : How can i get the complete URL of the current page

如何在不使用 window.location.href 的情况下在 angular 7 中获得完整的电流 URL?

例如,假设我目前的 URL 是 http://localhost:8080/p/drinks?q=cold&price=200

如何获得完整的 URL 而不仅仅是 /p/drinks?q=cold&price=200

我试过 this.router.url 这只给出 /p/drinks?q=cold&price=200 而不是完整的主机名。

我不想使用 window.location.href 的原因是它会导致 ng-toolkit/universal

中的渲染问题

我尝试遵循这个解决方案,它似乎与我有同样的问题并且还更新了

这是我的代码

windowProvider.js

import { InjectionToken, FactoryProvider } from '@angular/core';

export const WINDOW = new InjectionToken<Window>('window');

const windowProvider: FactoryProvider = {
  provide: WINDOW,
  useFactory: () => window
};

export const WINDOW_PROVIDERS = [
  windowProvider
];

app.module.ts

@NgModule({
    .......
    providers:[
    .......
    windowProvider
   ]
})

在我需要的页面中:

import {WINDOW as WindowFactory} from '../../factory/windowProvider';
......
 constructor(private router: Router, private helper: Helpers,
             @Inject(WindowFactory) private windowFactory: any,
            ) {
console.warn('HELLO I M WINDOW FACTORY', this.windowFactory.location.hostname);
}

买这个编译时出错

ERROR in ./src/app/factory/windowProvider.js 5:20 Module parse failed: Unexpected token (5:20) You may need an appropriate loader to handle this file type. | export const WINDOW = new InjectionToken('window'); |

const windowProvider: FactoryProvider = { | provide: WINDOW, | useFactory: () => window ℹ 「wdm」: Failed to compile.

任何人都可以告诉我如何解决这个问题。谢谢,

我关注的更多链接:

通用服务器端不知道window.location。

另一方面,Express 服务器从发送到服务器端的请求中知道 url。

所以我们需要将来自express的请求url注入angular..

server.ts

let template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();

app.engine('html', (_, options, callback) => {
    renderModuleFactory(AppServerModuleNgFactory, {
        document: template,
        url: options.req.url,
        extraProviders: [
            { provide: 'requestUrl', useFactory: () => options.req.url, deps: [] },    // 1. set up the provider for the url
            provideModuleMap(LAZY_MODULE_MAP)
        ]
    }).then(html => {
        callback(null, html);
    });
});

..以便在我们需要的地方检索它..

url-logger.ts

class UrlLogger {
    constructor(
        private window: Location,
        private injector: Injector,                         // 2. we need the injector to ..
        @Inject(PLATFORM_ID) private platformId: string,
    ) { }

    public log() {
        if (isPlatformServer(this.platformId)) {
            const requestUrl = this.injector.get('requestUrl');    // 3. ..retrieve the injected url
            console.log('server greets you via ' + requestUrl)
        } else {
            console.log('browser says hello from ' + window.location.href)
        }
    } 
}