【问题标题】:Display ContentFul RichText in Angular在 Angular 中显示 ContentFul RichText
【发布时间】:2020-01-13 13:03:00
【问题描述】:

我的 Angular 应用程序中有一个与 Contentful 相关的博客提要。感谢 Contentful javascript sdk。

https://www.contentful.com/developers/docs/javascript/tutorials/using-contentful-in-an-angular-project/

我正在尝试显示标题和文本字段。这是我的代码:

import { Component, OnInit } from '@angular/core';
import {Observable} from 'rxjs';
import {ContentfulService} from '../../services/contentful/contentful.service';
import { Entry } from 'contentful';

@Component({
  selector: 'app-blog',
  templateUrl: './blog.component.html',
  styleUrls: ['./blog.component.scss']
})
export class BlogComponent implements OnInit {
  private posts: Entry<any>[] = [];

  constructor(private postService: ContentfulService) {}

  ngOnInit() {
    this.postService.getPosts()
      .then(posts => {
        this.posts = posts;
        console.log(this.posts);
      });
  }
}

还有html:

<div *ngFor="let post of posts">
    <a href="#">{{ post.fields.title }}</a>
    <div>{{ post.fields.text }}</div>
</div>

title 字段显示良好,因为它只是一个字符串字段,但text 字段是 RichText 并显示 [object Object]。

实际上它包含几个对象。看起来对象被分成几部分。

https://www.contentful.com/developers/docs/concepts/rich-text/

有人已经在 Angular App 中显示 Contentful RichText 了吗? 有具体的方法吗?

【问题讨论】:

    标签: javascript angular typescript contentful


    【解决方案1】:

    我创建了一个可以使用 Angular 组件呈现富文本的 Angular 库:https://github.com/kgajera/ngx-contentful-rich-text

    为什么在@contentful/rich-text-html-renderer 上使用它?如果您需要自定义默认标记,它允许您使用您无法使用 documentToHtmlString 函数和 [innerHTML] 的 Angular 组件。

    【讨论】:

      【解决方案2】:

      首先,您必须从终端安装rich-text-html-renderer:

      npm install @contentful/rich-text-html-renderer
      

      然后,您可以从您的组件中导入它:

      import { documentToHtmlString } from '@contentful/rich-text-html-renderer';
      

      并使用它,就像这样:

      _returnHtmlFromRichText(richText) {
          if (richText === undefined || richText === null || richText.nodeType !== 'document') {
            return '<p>Error</p>';
          }
          return documentToHtmlString(richText);
      }
      

      最后,像这样从您的 html 中“调用函数”:

      <div [innerHtml]="_returnHtmlFromRichText(post.fields.text)">
      </div>
      

      您还可以添加一些选项来自定义富文本,更多信息here。此外,您应该在 Contentful 服务中编写类似于 _returnHtmlFromRichText 的函数,以便以后能够重用它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-24
        • 2018-07-30
        • 1970-01-01
        相关资源
        最近更新 更多