0

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

例如:

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

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

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

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

4

2 回答 2

2

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

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

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

于 2019-01-12T12:52:56.260 回答
0

您可以使用元服务从您的 API 更新元数据

在线示例

在此处输入图像描述

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-01-12T13:24:04.127 回答