【问题标题】:How to render html from server in angular 6 [closed]如何以角度 6 从服务器呈现 html [关闭]
【发布时间】:2019-01-12 11:59:56
【问题描述】:

我有一个客户端博客应用程序,它在加载时显示文章列表。我想从服务器加载文章数据,包括该页面的动态元标记以用于 SEO 目的

例如:

  1. 我点击一个链接:https://www.techstack21.com/article/function-returning-other-functions-in-javascript

我想使用查询字符串/?url=function-returning-other-functions-in-javascript 发出GET 请求,并从服务器到客户端呈现模板,类似于pugjade 模板引擎。

如何在 Angular 6 中实现这一点?

我不想在服务器上呈现完整的应用程序,而只是针对带有查询字符串的特定 url,如上例所示

【问题讨论】:

    标签: javascript angular angular6 angular-universal angular-seo


    【解决方案1】:

    这在 Angular 中是不可能的。您只能使用 [innerHTML] 在模板中渲染纯 HTML,但是您不能以角度方式与它交互。

    最好的做法是与服务器通信(使用 POST/GET 请求...),这将向您发送回您文章的序列化“JSON”数据。然后,您可以使用角度组件渲染从服务器接收到的未序列化 JSON 数据。

    您可能想看看 REST 应用程序。 :)

    【讨论】:

      【解决方案2】:

      您可以使用Meta Service 从您的 API 更新您的元数据

      online example

      import { Component } from '@angular/core';
      import { Meta } from '@angular/platform-browser';
      import { HttpClient } from '@angular/common/http';
      import { of } from 'rxjs';
      @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
      })
      export class AppComponent {
        name = 'Angular';
      
        constructor(
          private meta: Meta,
          private http: HttpClient
        ) { }
      
        getMetaData$() {
          const isDevMode = true;
          if (isDevMode) {
            const mockMetas = {
              ['twitter:card']: 'summary',
              'title': 'myTitle',
              'description': 'myDesc'
            }
            return of(mockMetas);
          } else {
            return this.http.get('/?url=function-returning-other-functions-in-javascript')
          }
        }
      
        ngOnInit() {
          this.getMetaData$().subscribe((metas) => {
            for (const key of Object.keys(metas)) {
              this.meta.updateTag(
                { name: key, content: metas[key] },
              );
            }
          })
        }
      }

      【讨论】:

        猜你喜欢
        • 2019-10-31
        • 2017-08-29
        • 2012-03-02
        • 2019-04-18
        • 2019-04-22
        • 2016-03-29
        • 2020-10-27
        • 1970-01-01
        • 2023-03-23
        相关资源
        最近更新 更多