【问题标题】:Include dynamic JSON data in Angular7 app在 Angular7 应用程序中包含动态 JSON 数据
【发布时间】:2019-05-14 04:26:37
【问题描述】:

我同时使用ng serve --watchng build --watch。使用 ng build,它会使用我的 index.html 文件,但是使用 ng serve,它似乎会忽略它。

现在,我正在 index.html 文件中渲染一些动态 JSON,如下所示:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>ApiApp</title>
  <base href="<%=base%>">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>

   <script type="text/javascript">

       const appData = JSON.parse('<%=json%>');

   </script>

  <app-root></app-root>
</body>
</html>

以上内容适用于ng build,但不适用于ng serve,因为ng serve 似乎没有包含此文件。

有没有更好的方法在首次加载应用程序时将动态 JSON 发送到 Angular7 应用程序?我的服务器可以在生产中将 JSON 渲染到 index.html,但在使用 ng serve 进行开发期间,它的工作效果并不好。

【问题讨论】:

    标签: javascript angular angular6 angular-cli angular7


    【解决方案1】:

    现在我只是放弃了 ng-serve,只使用 ng build --watch,然后使用 static-server(一个 npm CLI 工具),如下所示:

    "static-server": "cd dist/my-app && static-server --index index.html"
    

    我的 index.html 看起来像:

    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>ApiApp</title>
      <base href="/">
    
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="icon" type="image/x-icon" href="favicon.ico">
      <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.js"></script>
    
    </head>
    <body>
    
       <script type="text/javascript">
    
         define('app-data',() => {
           console.log('retrieving app-data...');
    
           let val = null;
           try{
             val = JSON.parse('<%=json%>')
           }
           catch(err){
             val = {routes: [1,2,3,4,5].map(v => ({val:v}))};
           }
    
           return {
             value: val
           }
         });
    
       </script>
    
      <app-root></app-root>
    </body>
    </html>
    

    requirejs 让我可以轻松加载动态代码,但我还没有弄清楚如何使用 Angular 来做到这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-29
      • 2015-04-04
      • 2017-12-24
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 2013-08-10
      相关资源
      最近更新 更多