首页 > 解决方案 > 在 Angular Universal 中的应用模块内获取 serverURL

问题描述

我收到错误 Http urls has to be absolute。这是因为我使用这个http.get('/env')应用程序在不同的环境中运行,所以 url 可以改变。所以我不能使用这个,例如http.get('http://test.com/env')我也不能使用 window.location.origin。因为我使用的是通用的。我该如何解决这个问题?

import { HttpModule, Http } from '@angular/http';

providers: [
    RootController,
    AuthService,
    AuthGuard,
    HttpRequestService,
    {
      'provide': APP_INITIALIZER,
      'useFactory': (http: Http) => {
        return () => {

          return new Promise((resolve, reject) => {
            const req = http.get('/env').pipe(map(env => env.json())).subscribe(config => {
              CONFIG.ORIGIN = config.ORIGIN;
              CONFIG.API_URL = config.API_URL;
              CONFIG.BASE_HREF = config.BASE_HREF;
              CONFIG.SOCIAL = config.SOCIAL;

              console.log(CONFIG);

              resolve(CONFIG);
            }, error => {
              reject(error);
            });
          });
        };
      },
      'deps': [Http],
      'multi': true
    },
  ],
  bootstrap: [AppComponent]

服务器.ts

// These are important and needed before anything else
import 'zone.js/dist/zone-node';
import 'reflect-metadata';

import { enableProdMode } from '@angular/core';

import * as express from 'express';
import { join } from 'path';


// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();

// Express server
const app = express();

const PORT = process.env.PORT || 3000;
const DIST_FOLDER = join(process.cwd(), 'dist');

// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main');

// Express Engine
import { ngExpressEngine } from '@nguniversal/express-engine';
// Import module map for lazy loading
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';

app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [
    provideModuleMap(LAZY_MODULE_MAP)
  ]
}));

app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));

// TODO: implement data requests securely
app.get('/api/*', (req, res) => {
  res.status(404).send('data requests are not supported');
});

// Server static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));

// All regular routes use the Universal engine
app.get('*', (req, res) => {
  res.render('index', { req });
});

// Start up the Node server
app.listen(PORT, () => {
  console.log(`Node server listening on http://localhost:${PORT}`);
});

标签: angularangular-universal

解决方案


尝试这样的事情

  1. 提供来自 Angular 通用服务器的服务器 url

服务器.ts

编辑这里是使用快递引擎的版本

//...

// All regular routes use the Universal engine
app.get('*', (req, res) => {

  //let serverUrl = req.protocol + '://' + req.get('host');
  let serverUrl = `http://localhost:${PORT}`;
  res.render('index', 
  { req, 
    res, 
    bootstrap: AppServerModuleNgFactory,

    providers: [
        provideModuleMap(LAZY_MODULE_MAP),
        {
          provide: 'serverUrl',
          useValue: serverUrl
        }
    ]

    });
});

结束编辑

服务器.ts

(不使用快递引擎)

app.engine('html', (_, options, callback) => {
let serverUrl = options.req.protocol + '://' + options.req.get('host');

  renderModuleFactory(AppServerModuleNgFactory, {
    //...
    extraProviders: [
      provideModuleMap(LAZY_MODULE_MAP),
      {
        provide: 'serverUrl',
        useValue: serverUrl
      }
    ]
  }).then(html => {
    //...
  });
});
  1. 使用提供的值角边

app.module.ts

import {Optional, InjectionToken} from '@angular/core';
import { HttpModule, Http } from '@angular/http';
const ServerUrl = new InjectionToken('serverUrl');


//...
providers: [
RootController,
AuthService,
AuthGuard,
HttpRequestService,
{
  'provide': APP_INITIALIZER,
  'useFactory': (http: Http, serverUrl: string) => {
    return () => {

      return new Promise((resolve, reject) => {
         //serverUrl will be empty client side, and contain server URL when using angular universal
        const req = http.get((serverUrl || '') + '/env').pipe(map(env => env.json())).subscribe(config => {
          CONFIG.ORIGIN = config.ORIGIN;
          CONFIG.API_URL = config.API_URL;
          CONFIG.BASE_HREF = config.BASE_HREF;
          CONFIG.SOCIAL = config.SOCIAL;

          console.log(CONFIG);

          resolve(CONFIG);
        }, error => {
          reject(error);
        });
      });
    };
  },
  'deps': [Http, [new Optional(), ServerUrl] ], //<= optional dependency
  'multi': true
},
],
bootstrap: [AppComponent]

推荐阅读