【问题标题】:Pass data from server side to client without http call无需http调用即可将数据从服务器端传递到客户端
【发布时间】:2020-04-07 03:03:55
【问题描述】:

我将 Angular Universal 和 node.js 开发为服务器应用程序。我按照每个人的建议做所有事情,包括官方文档。

通常在加载客户端应用程序时,它会对 API 执行 ajax 查询。 API放置在我的服务器上。 我的目标是避免这个 ajax 调用并使用这些数据从服务器呈现页面。

我像典型的例子一样尝试:

ngOnInit() {
      let myTransferStateKey = makeStateKey<any>("myDatas");

      if(this.transferState.hasKey(myTransferStateKey)) {
          this.result = this.transferState.get(myTransferStateKey, {});
          this.transferState.remove(myTransferStateKey);
      } else {
          this.http.get("link-to-api").subscribe(response => {
              this.result = response;
              this.transferState.set(myTransferStateKey, this.result);
          });
      }
  }

据我了解,以下代码将在服务器端执行:

      this.http.get("link-to-api").subscribe(response => {
          this.result = response;
          this.transferState.set(myTransferStateKey, this.result);
      });

那么服务器端会对自己的服务器执行真正的http查询吗?太丑了!理想情况下,我应该只在我的服务器上使用服务并将数据传递给查看,然后服务器将使用这些数据将 html 呈现给客户端。我希望你知道我的意思..

这也是我的 server.ts,你最有可能在网上看到的典型代码:

import 'zone.js/dist/zone-node';
import 'reflect-metadata';

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

import * as express from 'express';
import { join } from 'path';
import { readFileSync } from 'fs';
import { AppServerModule } from './src/main.server';

import {ngExpressEngine} from '@nguniversal/express-engine';

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

// Express server
const app = express();

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

// Our index.html we'll use as our template
const template = readFileSync(join(DIST_FOLDER, 'browser', 'index.html')).toString();

const domino = require('domino');

const window = domino.createWindow(template);

global['window'] = window;
global['document'] = window.document;

global['requestAnimationFrame'] = cb => cb();

app.engine('html', ngExpressEngine({
    bootstrap: AppServerModule,
}));

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

// 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(join(DIST_FOLDER, 'browser', 'index.html'), { req });
});


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

那么如何优雅地解决呢?我喜欢这种通用方法和服务器端渲染,但它现在看起来对我来说很潮湿。

我使用 angular 9 版本,node.js 12 版本...

让我澄清和阐述这个想法和问题:如何为客户端和服务器使用单一服务(相同的类/文件等)?唯一的区别应该是服务器将直接使用服务,但客户端在需要获取数据时 - 将使用 ajax 请求到 API,而在服务器端 - 将使用此服务类)我必须使其与服务器一起工作。 ts 之类的……

【问题讨论】:

    标签: angular angular-universal


    【解决方案1】:

    所以我认为你在说 Angular Universal 与 NodeJS 应用程序之间存在混淆。

    Angular Universal 呈现服务器上请求的第一个页面,从那时起,当您在站点周围单击时,它就像一个常规的 Angular 应用程序一样。这实际上只是给人一种错觉,即第一次“绘制”非常快,因为您几乎可以在访问站点后立即完全呈现整个页面,而不是常规的 Angular 应用程序,在那里您会获得某种空白页面,然后作为您的订阅返回您填写页面等。

    如果您希望事物始终在服务器端呈现,那么您可能正在考虑创建一个返回 HTML 视图的标准 Express NodeJS 应用程序,而不是 Angular Universal。

    如果你真的想继续使用 Universal。然后您可以使用称为“isPlatformBrowser”和“isPlatformServer”的角度方法来检查您是在服务器上还是在浏览器上运行,然后您可以有逻辑来调用API或直接获取数据。

    例如:

    export class PostfeedComponent implements OnInit {
    
      constructor(@Inject(PLATFORM_ID) private platform: Object) { }
    
      ngOnInit() {
          if (isPlatformBrowser(this.platform)) {
            // here you can run any browser specific code
          } else {
             // Runs only on server
          }
      }
    }
    

    更多信息:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多