以角显示ContentFul RichText

问题描述 投票:1回答:1

我在Angular App中有一个与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应用中显示Contentful RichText吗?有特定的方法可以做到吗?

javascript angular typescript contentful
1个回答
0
投票

首先,您必须从终端安装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的函数,以便以后可以重用。

© www.soinside.com 2019 - 2024. All rights reserved.