I'm encountering an issue with storing my service data in an Array using Angular

I am currently working on a project where I need to fetch images from a service and store them in an array. The goal is to create a sliding image feature within my application using this array.

Below is the component file:

import { Component, OnInit, Input } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
head_slider: any = [];
imgslider: any = [];

  constructor( public http: HttpClient ) { }

  slides  = [  ];

slideConfig  = {'slidesToShow': 4, 'slidesToScroll': 4};

  ngOnInit() {

  this.http.get('https://newsapi.org/v2/top-headlines?country=in&apiKey=69e4c9820959482e8c40e42f8bcfe975').subscribe(data => {
    this.head_slider = data['articles'];

   console.log(this.head_slider);
   this.slides.push( 'img :' + this.head_slider.urlToImage);
  });

  }

addSlide() {
  this.slides.push({img: 'http://placehold.it/350x150/777777'});
}

removeSlide() {
  this.slides.length = this.slides.length - 1;
}

afterChange(e) {
  console.log('afterChange');
}

}

The objective of the code above is to extract key-value pairs containing images from the service and push them into an array named slides = [ ]; , In this format --- > slides = [ img: , img: , img: ];

Here is the HTML file corresponding to the component:

<ngx-slick class="carousel" #slickModal="slick-modal" [config]="slideConfig" (afterChange)="afterChange($event)">
        <div ngxSlickItem *ngFor="let slide of slides" class="slide">
              <img src="{{ slide.img }}" alt="" width="100%">
        </div>
    </ngx-slick>

    <button (click)="addSlide()">Add</button>
    <button (click)="removeSlide()">Remove</button>
    <button (click)="slickModal.slickGoTo(2)">slickGoto 2</button>
    <button (click)="slickModal.unslick()">unslick</button>

Answer №1

To properly access the content of head_slider, you must iterate through it as it is an array.

ngOnInit() {

    this.http.get('https://newsapi.org/v2/top-headlines?country=in&apiKey=<<api key here>>').subscribe(data => {
        this.head_slider = data['articles'];
        for(let i = 0; i < data['articles'].length; i++){
            this.slides.push({img: data['articles'][i].urlToImage})
        }
    });

}

Answer №2

Can you kindly update

this.slides.push( this.img = this.head_slider.urlToImage)

to

this.slides.push( {img: this.head_slider.urlToImage}); 

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

Maintain the variable name when using destructuring in JavaScript/TypeScript

Can variable names and destructuring be used together in a single command in JavaScript/TypeScript? For example: function stopTheCar(car & { speed } : Car) { if (speed > 10) car.stop() } The closest option available is to use destructuring in a ...

What is the best way to invoke a function that is declared within a React component in a TypeScript class?

export class abc extends React.Component<IProps, IState> { function(name: string) { console.log("I hope to invoke this function"+ name); } render() { return ( <div>Hello</div> ); } } Next, can I cal ...

Emphasize a portion of a text / Apply formatting to a variable

I am facing an issue where I need to format only the date in a specific string. I have managed to extract the date and store it in a variable after isolating it from the original message. <div class="foo"><p> Click here now and get by January ...

Implementing restrictions for each duplicated field using jQuery: A step-by-step guide

Is there a way to limit the number of words in each duplicated field using jQuery? I want to restrict users from entering more than 5 words per field. I have a snippet of code, but it's not quite working as expected. Can anyone provide some assistanc ...

The unit test is not passing due to inconsistencies between the mock data generated in the constructors and the original mock data

Currently, I am delving into the world of unit testing and have created a test to work on. Here is what I have so far: const EXEPECTED: MergedFood = { id: '1', name: 'test mergedFood', ingredients: { '2': ...

A simple guide on how to send an Angular component to the Nebular dialog service

My current project involves creating a web dialog in Angular6 using Nebular components. Initially, I used the method of passing an <ng-template> reference in the following manner: openAddDialog = (dialogTemplate: TemplateRef<any>) => { ...

Using Typescript: How to pass a function as an argument in another function

In my angular application, I am working on the following setup: this.myServiceOne.getDataOne().subscribe((res => {this.variableOne= res})); this.myServiceTwo.getDataTwo().subscribe((res => {this.variableTwo= res})); this.myServiceThree.getDataThree( ...

What is the most efficient method for saving and accessing the distances between different cities?

Hello, I am a newcomer to Java and looking for guidance on using basic and straightforward Java methods to comprehend your idea quickly. Issue: I have n cities, each with a unique name, all interconnected with distances between them. What is the most effi ...

The MdDialog in Angular2 is failing to display as a pop-up on the screen

I am currently facing an issue with the MdDialog in my code. Instead of showing up as a popup, it is displaying as a block at the bottom of the page. What steps should I take to troubleshoot and fix this problem? code snippet below common-modal.componen ...

Switching video sources with jQuery and HTML5 can be achieved by clicking on an

I need to develop an engaging video using HTML5 and jQuery. My objective is to: Start playing video1 Show button1 when video1 finishes, then switch to video2 upon clicking and hide button1 Play video2 Display button 2 after video2 ends, then change to vi ...

Exploring the varying treatment of the noscript tag across different web browsers

I've been searching everywhere, but I can't find any information on this topic. What I really want to understand is what browsers do with the content inside a noscript tag when JavaScript is enabled. Let's consider an example: According t ...

What is the solution for resolving array items in a GraphQL query?

I am facing an issue with my graphql Query, specifically in trying to retrieve all the fields of a Post. { getSpaceByName(spaceName: "Anime") { spaceId spaceName spaceAvatarUrl spaceDescription followin ...

The error message, "The type 'boolean' is not a valid index type," indicates that using the data

While attempting to upgrade Angular 11 to Angular 13, I encountered an issue where I received the error message: "Type 'boolean' cannot be used as an index type." Can someone advise on what changes need to be made in the following code snippet? [ ...

Persist a SQL entity to a document with the help of Node.js

I am looking for a way to store the data from the rows object either in a file or as a JSON file. app.get('/getposts', (req, res) => { mysqlConnection.query('Select * from posts', (err, rows, fields) => { if (!err) console.l ...

Utilize Angular to inject an input from a component directly into the header of my application

I am looking to customize my Pages by injecting various components from different Pages/Components into the header. Specifically, I want to inject an Input search field from my content-component into the header Component. I initially attempted to use ng-Co ...

Encountering surprising console errors with Protractor while executing tests that include Selenium code

Starting a new Angular 4 project, I utilized ng new [myProjectName] to set up the foundation and generate Components using ng g c [componentName]. Allowing the Angular command-line framework to take care of essential tasks like generating spec ts files and ...

Expressjs in Node.js provides the quickest method for storing and showcasing an HTML page

Looking to showcase a static HTML page using expressjs. Wondering about the quickest method to accomplish this. My current approach involves storing an html file in the file system and utilizing res.sendfile(home + "/public/file.xml") Is sendfile my best ...

The Symfony API failed to generate a response

There seems to be a problem when trying to link the Symfony API with a React application. The API is not providing any response, even though it works fine when accessed directly through the link. ApiDirectURL Fetching this data from the React app is yiel ...

One cannot adjust the opacity of the arrow in ionic 4 ion-item details

Currently, I am dealing with a project that was not originally coded by me and have come across an issue that is proving to be challenging to resolve. Please review the code snippet below: <ion-item detail *ngIf="c.cv" [routerLink]="[&ap ...

Vue.js: Trouble with updating the v-for list

Here is a list I have: <ul id="tab"> <li v-for="list in names"> {{ list.personName }} </li> </ul> And then, I have this Vue object set up: var vm = new Vue ({ el: '#tab', data: { ...