Separating HTML content and text from a JSON response for versatile use within various sections of an Angular 2 application using Typescript

Hello there! I am currently utilizing Angular 2 on the frontend with a WordPress REST API backend. I'm receiving a JSON response from the service, however, the WP rest API sends the content with HTML tags and images embedded. I'm having trouble separating this content to use it in my HTML format. I would like the image and text to be displayed in different sections, and also remove the

tag from the content.

Here is an example of the service:

@Injectable()
export class VtkraHomeService {
    private url = 'http://myapplication.com/wp-json/wp/v2/posts';
    private headers = new Headers({'Content-Type': 'application/json'});
    constructor (private http : Http){

    }

    getFeeds(){
        return this.http
        .get(this.url)
        //.then( (res) => res.json);
        .map((res: Response) => res.json());
    }

And here is an example component:

export class HomeComponent implements OnInit { 

  homefeed: any;
  showLoader = false;

  constructor( private VtkraHomeService: VtkraHomeService ) {  }

getHomeFeeds(){
  this.showLoader = true;
  this.VtkraHomeService
  .getFeeds()
  .subscribe(data => {
    this.homefeed = data;
    console.log(this.homefeed);
    this.showLoader = false;
  });
}



  ngOnInit(){
    this.getHomeFeeds()
  }

}

My issue lies in the JSON response structure which looks something like this:

    [
       {
          id: 15953,
          date: '2016-10-22T07:55:34',
          title: {
                   rendered: 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum',
                   protected: false
                 },
          content: {
                    rendered: '<p><img src="https://www.w3schools.com/css/paris.jpg" alt="w3c" />Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled ...                    
                    },
           link: 'htts://www.w3schools.com/css/paris',
           type: 'post',
           author: 1
       },
{
   // More items...
}
    ];

I aim to extract the HTML and text separately from the "content (rendered)" field.

content: {
           rendered: '<p><img src="https://www.w3schools.com/css/paris.jpg" alt="w3c" />Lorem Ipsum is simply dummy text of the printing....
           protected: false
         },

The desired HTML format for displaying the content should look like this:

<md-list class="home-feed-list">
  <div *ngFor="let item of homefeed">
  <md-list-item routerLink="/Story">
  <img md-list-avatar src="item.content.rendered(image url)" alt="" class="list-avatar">
  <h4>{{item.title.rendered}}</h4>
<p>{{item.content.rendered(remaining text)}}</p>
  </md-list-item>
  <md-divider></md-divider>
  </div>
</md-list>

If anyone can provide guidance on how to achieve this properly, I would greatly appreciate it as I am still learning about Angular 2 and Typescript.

Answer №1

If you want to extract specific information from a rendered string, you can utilize the DOM API to create an object and fetch the necessary data. This process can be done in your view-model after receiving the data from a service, allowing you to structure your model accordingly (such as creating a homefeed with objects containing images and text).

Below is a straightforward example:

var contentRendered = '<p><img src="https://www.w3schools.com/css/paris.jpg" alt="w3c" />Lorem Ipsum is simply dummy text of the printing and typesetting industry...';

// Convert rendered text into a DOM object
var template = document.createElement("template");
template.innerHTML = contentRendered;

// Use DOM API to retrieve necessary data
var imgPart = template.content.firstChild.querySelector("img");
var text = template.content.firstChild.innerText;

console.log(imgPart);
console.log(text);

Alternatively, you can implement this functionality in custom AngularJS filters, adapting the rendering process accordingly. Even if I'm not well-versed in AngularJS, resources like this link suggest that such techniques are feasible.

I hope this guidance proves useful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting input tag to a method in component with uppercase transformation

Currently, this code resides within the <input tag I am looking to convert this code into a method in my component. Any ideas on how to do this? oninput="let p=this.selectionStart; this.value=this.value.toUpperCase(); this.setSelectionRange(p,p) ...

What is the best way to store values in a map for future reference within a Kotlin class?

Looking to implement a map of key value pairs in Kotlin inside a class that is mutable and can be updated and referenced as needed. Research suggests that using a MutableMap would be the appropriate choice, given its ability to be updated at any point. I ...

JSONPath encounters an issue when square brackets are embedded within a string

I am encountering issues with the JSONPath library found at https://github.com/JSONPath-Plus/JSONPath in its latest version. For example: { "firstName": "John", "lastName": "doe", "age": 26, ...

The type '{}' is lacking the specified attributes from type 'RouteComponentProps<{},,>'

As a newcomer to React and Typescript, I'm in the process of familiarizing myself with both. Please bear with me as I navigate through this learning curve! index.tsx Router.tsx (containing all route definitions) LandingFrame.tsx (defining the page la ...

Tips for troubleshooting common network errors in Volley

When attempting to access this function through WiFi, it works fine. However, when using a mobile network, I encounter the following error: D/Volley: [3641] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] 0x95bac5ee NORMAL 14> * 2020-0 ...

Having trouble configuring custom SCSS Vuetify variables with Vue 3, Vite, Typescript, and Vuetify 3

Having some trouble with custom variables.scss in Vuetify. Looking to make changes to current settings and added my code on stackblitz. Check it out here Been going through Vuetify documentation but can't seem to pinpoint the issue. Any assistance w ...

using javascript to initiate an ajax request

Apologies if my question seems confusing, I am currently in the process of grasping ajax, JavaScript, and jQuery. Here is my query: Below you can find a snippet of my javascript code: if (colorToCheck == gup("Player1")) { document.getElementById(&apo ...

Guidelines for formatting AJAX in Django

When it comes to making an ajax request, there seems to be two schools of thought. Some people prefer using a returning render_to_string in Python to handle all the formatting with the template language, like so: return render_to_string('calendar.htm ...

Why does it seem like Typescript Promise with JQuery is executing twice?

Figuring out Promises in Typescript/JS seemed to be going well for me, but I've hit a roadblock. I've set up Promises to wait for two JQuery getJSON requests to finish. In my browser, when connecting to a local server, everything functions as ex ...

Attempting to transform my JSON data into a string, only to encounter the frustrating result of "[object Object]

Trying to display the subData in Angular is causing me to see [object Object] instead: View image here I've defined a model that includes an array of sites: public class Site { public int Id { get; set; } public string Name { get; ...

Encountering a TypeScript error in Next.js: The 'Options' type does not align with the 'NavigateOptions' type

My code snippet: import { useRouter } from 'next/navigation'; interface Options { scroll: boolean; } const Component = () => { const router = useRouter(); const updateSearchParams = () => { const searchParams = new URLSearchPa ...

Encountered a hiccup during the installation of ssh2-sftp-client on Next.js

I'm looking for a way to save uploaded files in my domain's storage using SFTP. I came across the multer-sftp package, but when I attempted to run the command yarn add multer-sftp ssh2-sftp-client, I encountered a strange error with the second pa ...

The TypeScript `unknown` type restricts the use of non-unknown types in function parameters

Why is there an error in this code? const x: unknown[] = ['x', 32, true]; // OK const y: (...args: unknown[]) => unknown = (xx: number) => {}; // ERROR // Type '(xx: number) => void' is not assignable to type '(...args: u ...

Having trouble with JSON/jQuery syntax?

I am attempting to populate a set of DIVs with image backgrounds by reading images from a specific folder. The jQuery code I have written is shown below: $.getJSON('../functions.php', function(images) { images.each( function() { $('#m ...

Enhancing the theme using material-ui@next and typescript

While developing my theme using material-ui, I decided to introduce two new palette options that would offer a wider range of light and dark shades. To achieve this, I extended the Theme type with the necessary modifications: import {Theme} from "material ...

The struggle of encoding: Making a JSON ajax call (utf-8) to convert Latin1 characters to uppercase

I've encountered a particular issue: the Javascript library I am developing utilizes JSON cross-domain requests to fetch data from a backend powered by Ruby on Rails: function getData() { $.ajaxSetup({ 'beforeSend': function(xhr) {xhr.s ...

The attribute 'tableName' is not found within the 'Model' type

Currently in the process of converting a JavaScript code to TypeScript. Previously, I had a class that was functioning correctly in JS class Model { constructor(input, alias) { this.tableName = input; this.alias = alias; } } Howev ...

What is causing the Jackson ObjectMapper Parsing Error stemming from problems with initializing a LinkedHashMap?

I am trying to parse this JSON data using the ObjectMapper library: { "basePath": "/v1", "models": { "Course":{ "number": "integer", "name": "string", "description": "string" }, "Department": { "name": "string", ...

Retrieve Gravatar image using JSON data

I am currently working on extracting data to show a user's Gravatar image. The JSON I have is as follows: . On line 34, there is 'uGava' which represents their gravatar URL. Ideally, it should be combined with / + uGava. Currently, I have ...

Switching Facebook accounts on Firebase

I'm currently working on an Angular2 App that utilizes Firebase as its User system, with authentication providers including Email + Password, Facebook, and Google. One issue I have encountered is that when logging in with Facebook, I am unable to swi ...