Ways to retrieve object array values

How can I extract object array values from a data array? Here is the code I am using:

Component

FmtNews(mediasource) {
    let body = mediasource;
    console.log("Testing body:" +body)
    this.commonService.getTopNews(body)
    .subscribe((res) => {
      if (res['status'].code === 102) {
        // this.headerService.isLoading = false;
         console.log(res['data'])
      }
    });
}

When I run console.log(res['data']), I receive output like this:

(4)[..]
 0: Object (mediaSource: "News Today", pageUrl: "https://www.newstoday.com", contents:)
 1:Object (mediaSource: "News Today", pageUrl: "https://www.newstoday.com", contents:)
 2:Object (mediaSource: "News Today", pageUrl: "https://www.newstoday.com", contents:)
 3:Object (mediaSource: "News Today", pageUrl: "https://www.newstoday.com", contents:)

My issue is... How do I access the data within these objects to display on an HTML page?

HTML

<div class="media">
  <img class="mr-3" src="..." alt="Generic placeholder image">
  <div class="media-body">
    <h5 class="mt-0">title here</h5>
    <span>url here</span>
    <div>
    contents here
    </div>
  </div>
</div>

Answer №1

To access and use the response in HTML, you can first declare a local variable and assign the response to it:

list: any[] = []; <-- this line here

FmtNews(mediasource) {
    let body = mediasource;
    console.log("Test body:" +body)
    this.commonService.getTopNews(body)
    .subscribe((res) => {
      if (res['status'].code === 102) {
         this.list = res['data'];
         console.log(res['data'])
      }
    });
}

In your HTML code:

<div *ngFor="let obj of list">
   {{obj.mediaSource}}
</div>

Alternatively, if you want to display the mediaSource as a title:

<div>{{ list[0]?.mediaSource }}</div>

This will show the mediaSource property of the first item!

EDIT

<div class="media" *ngFor="let obj of list">
  <img class="mr-3" src="..." alt="Generic placeholder image">
  <div class="media-body">
    <h5 class="mt-0">{{ obj.mediaSource }}</h5>
    <span>{{ obj.pageUrl}}</span>
    <div>
    {{ obj.contents}}
    </div>
  </div>
</div>

Answer №2

Save the information to a variable this.data=res['data']

In your HTML,

<div class="media">
  <img class="mr-3" src="..." alt="Generic placeholder image">
  <div class="media-body" *ngFor="let obj of data">
    <h5 class="mt-0">{{obj.mediaSource}}</h5>
    <span>{{obj.pageUrl}}</span>
    <div>{{obj.contents}}</div>
  </div>
</div>

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

"Addressing the Flash of Unstyled Content (FOUC) in Angular Universal during

My universal app is experiencing a strange issue where, during the swap from server side to client side app, there is a momentary lapse in styling for certain components within my routed component. This results in an initial flash of unstyled content (FOUC ...

Utilizing Angular 4's routing feature to pass parameters just like a

Greetings! I hope you are doing great. Currently, I am working on building an application using Angular 4 and I am facing a challenge regarding passing parameters in my routes, similar to how POST parameters are passed in HTTP requests. Can anyone provide ...

What is the process for monitoring a property in Angular?

Seeking clarification on Angular - is it possible to detect property value changes within the same class? import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', ...

Setting up the view for 2-factor authentication in Umbraco 10: A guide for Angular or C# users

In my efforts to customize the two-factor authentication view for users with 2FA enabled in Umbraco, I've created a provider called UmbracoUserAppAuthenticator and used builder.Services.Configure to add the 'SetupViewPath', which is function ...

Best practices for managing Entity Framework models with mandatory navigation property for efficient data transfer

Within my database, there are two tables: Configuration (parent) id (PK) Name ConfigurationAlert (child) id (PK) ConfigurationId (PK, FK Configuration) Message By using custom templates and scaffolding in Entity Framework Core, I ha ...

What is the best way to include custom RequestOptionsArgs in an Angular 2 request?

My customized Http service includes a method that handles requests with a loading indicator that displays when the request begins and hides when it ends. request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> { this.loa ...

Incorporating JSON data into a reactive form group with nested objects and form arrays within nested components in Angular 13

After receiving JSON data from the backend and converting it into my model classes (which include nested classes and arrays), I encountered an issue while trying to create a reactive FormGroup by initializing it with my model class. The problem arose when ...

Extract the checkbox value within a table

I'm facing a challenge with a table that has multiple columns and a checkbox for one of the columns. Table layout: https://i.sstatic.net/qKZHt.png I attempted to assign some formControlName to the checkbox within the table, but I received an error ...

Whenever attempting to execute a protractor test using cucumber, a specific error message is displayed reading: "E/launcher - Process exited with error code 1"

Looking for some assistance. I seem to be stuck and can't pinpoint the issue. Package.json { "devDependencies": { "@cucumber/cucumber": "^7.0.0", "@serenity-js/core": "^2.25.7", "@s ...

Using TypeScript, creating a tagged template literal for running Jest tests with the `test.each`

Struggling to construct a jest test.each with a tagged template literal test.each` height | text ${10} | ${undefined} ${20} | ${undefined} ${10} | ${'text'} ${20} | ${'text'} `('$height and $text behave as expected&a ...

Ways to effectively coordinate values between parent and child elements in Angular/PrimeNG

Hi there. I've been exploring the relationship between parent and child components in Angular, specifically regarding bind propagation. It's not behaving as I anticipated, even after reviewing the documentation. You can find the full code here ...

Uncertain about where and how to properly register a service in Angular 2

All: Today was my first day diving into Angular2, as I embarked on the official TUTORIAL at part 6: Routing Around the App https://angular.io/docs/ts/latest/tutorial/toh-pt5.html Within the Create AppComponent section, it is mentioned: Add HeroService ...

Best practice for incorporating the cq-prolyfill third-party JavaScript library into an Angular 5 application

I'm experiencing an issue with the cq-prolyfill library not functioning properly when included through a typescript import statement within an angular module. I have confirmed that it is included in my vendor bundle, but for some reason the initial se ...

`It is important to note that in Tailwind CSS, `h-8` does not supersede `h-4

I developed an Icon component that looks like this: import { IconProp, library } from "@fortawesome/fontawesome-svg-core"; import { far } from "@fortawesome/free-regular-svg-icons"; import { fas } from "@fortawesome/free-solid-svg- ...

Angular 2 (Final): Utilizing resetConfig for seamless integration of routes into lazy loaded modules

Trying to understand the process of dynamically adding routes from a lazy-loaded module. The core app has initial routes: export const routes = [{ path: "", component: HomeComponent }, { path: "moduleA", loadChildren: "app/moduleA/A.module ...

The incorrect initial state is causing issues in the Zustand state management on the Next.js server side

While utilizing zustand as a global state manager, I encountered an issue where the persisted states were not being logged correctly in the server side of nextjs pages. The log would only show the default values (which are null) and not the updated state v ...

What is the best way to retrieve a value from async/await functions?

async function fetchNetworkStatus() { const network = await Network.getConnection(); setConnection(network.isConnected); console.log(connectionStatus); if (network.isConnected) { return true; } else { ...

How to align text in the center of a card using Angular Bootstrap

I have a column div that I need to center the text in Here is my code: <div class="card mb-4"> <div class="card-header"> <div class="card-title-wrap bar-info"> ...

Having trouble establishing a connection to the TyreORM Module database while using a Postgres Docker image

I am currently developing a NestJS Application and have integrated TypeORM to connect with my local database. The database is a postgres image running in the background. Although I am able to connect to the image using pgAdmin, I am encountering an error ( ...

I'm experiencing a strange issue where my React component renders twice in production mode, despite having strict mode turned off. Can anyone advise me on

Within my layout.tsx, I have a structure that encloses the page with a container div and introduces a separately defined TopBar component alongside. The functionality seems fine, but an issue arises where the component is created before the {children}, as ...