[英]How do I parse html elements from an observable array of objects in rxjs
在角度8中,我正在解析wordpress rss提要,並使用其屬性之一“內容”來構建新聞滾動器。 使用來自node.js的rss-parser將rss feed處理為javascript對象。
我需要從(p)元素之間解析出一個http鏈接,一個圖像和一些字符。 我的問題是我需要的數據包含在'content'屬性中,我不知道編碼或如何解析鏈接,圖像和文本並將它們放入可觀察范圍內的變量中。
使用Angular和rxjs,我能夠派生一個包含每個文章和所需屬性的對象數組。 const http$ = this.api.rssSource$();
這是從有角度的api.service.ts獲取提要並返回一個observable。 然后,使用以下代碼將其映射到對象數組:
this.newsItems$ = http$ .pipe( map(res => Object.values(res['items'])));
我得到這20個項目的數組
(20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
上面數組中的每個對象如下所示:
{content: "<a href="https://example.com/"><img width="300" height="200" src="https://example.com/some-image-300x200.jpeg" alt="blah blah blah" /></a><p>A lot of text about something and then something else</p><br /><p>jabber jabber and more jabber</p>↵<p><a href="https://example.com/example.html/" rel="nofollow">...Read More About Blah And Jabber</a></p>↵}
在有角度的模板中使用<div [innerHTML]="item.content"></div>
,我可以使用圖像和大量文本來呈現html。 但是,它不是我想要的格式,需要縮短和重新排列。 我只需要完整的'a href =“ https:// xxx ...”','img src =“ http:// xxx ...”'和單個'p xxxx / p'。
如何訪問該對象,以便可以進一步對其進行解析以填充newsLink,newsImg,shortDes的變量?
如果你希望做的是操縱發射陣列中的每個對象,你可以添加一個陣列map
的RxJS內部呼叫map
電話:
this.newsItems$ = http$.pipe(
map(res => Object.values(res['items']).map(item => {
// do item modification here
}))
);
這將返回修改后的數組。 另外,您可以拆分數組並將其作為單個值發出,然后RxJS map
它們以對其進行修改:
this.newsItems$ = http$.pipe(
switchMap(items => from(items)),
map(item => // manipulate individual items here)
);
至於實際的解析本身,可以使用正則表達式和match()
函數來實現:
arrayOfAnchorTags = item.content.match(/<\s*a[^>]*>(.*?)<\/\s*\s*a>/g);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.