Navigating through an Angular 2 service

I'm struggling to retrieve an array from a JSON API and then loop through it. I can't seem to grasp how it all fits together. Any guidance would be greatly appreciated.

This is what my service looks like:

import {Injectable} from '@angular/core';
import { Http } from "@angular/http";
import "rxjs/Rx";

@Injectable()
export class PlayersService {
    roster:Roster[];

    constructor(private http: Http){
        this.roster = [];
    }


    getPlayer(id) {
       for (let player of this.roster) {
            console.log(player["id"]);
        }   
    }


    getRoster(season,category) {
        this.roster.push(this.http.get("http://API JSON LIST OF ID")
            .map(res => res.json()));
    }

}

interface Roster {
    id:number
}

This is how I invoke it:

ngOnInit() {
   this.getRoster();
   this.getPlayers();
}

Can someone point out where I'm going wrong?

Answer №1

Here is a solution that should meet your requirements:

@Injectable()
export class PlayersService {
    roster:Roster[];

    constructor(private http: Http){
        this.roster = [];
    }

    getPlayer(id) {
       for (let player of this.roster) {
            console.log(player["id"]);
        }   
    }

    getRoster(season,category) {
        return this.http.get("http://API JSON LIST OF ID")
       .map(res => res.json())
       .do(val => this.roster.push(val));  // the do operator should be used for side effects (eg modifying an existing array)
    }
}
ngOnInit() {
   this.playerService.getRoster().subscribe(val => this.playerService.getPlayer());
}

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

Update the parent element's class style within a targeted div media query

I am facing a challenge where I want the width of my .container element to be 100% when the screen size reaches 900px. The issue is that I have used .container on multiple pages and only wish to change its appearance within the #sub-top div. The terminolo ...

Is the JSON data missing from the POST request?

I'm having trouble inserting data into the database using a POST request. Here is how I'm making the request: 127.0.0.1:3000/api/users?fname=asd&lname=edc&<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d7870 ...

troubles arise when using undeclared functions in javascript

Recently, I've been working on implementing a Javascript CountDown Timer triggered by a button click. The Javascript code is stored in an external file, as well as the CSS for styling the timer. The problem arose when I tried including the Javascript ...

Implementing AngularJS JQuery Datatables Directive for Displaying Multiple Data Tables within a Single View

I have successfully implemented the following directive: angular.module('myApp').directive('jqdatatable', function () { return { restrict: 'A', link: function (scope, element, attrs, ngModelCtrl) { ...

Display the inputs from a reactive form in a different component

I am currently facing a situation where I have multiple components, such as component A, containing a reactive form. The data from these forms is stored in a central service. My goal now is to display a preview of this form in component B. However, upon na ...

Using a custom filter in AngularJS allows for seamless data filtering directly from the initial dataset

My goal is to implement a custom filter that will allow me to filter data based on a search word. The scope attribute gets populated in the controller's scope as shown below: naApp.controller('naCareNewTicketCtrl', ['$scope', &apo ...

Bot on Discord engaging in a gaming session

I recently developed a Discord bot with the status of ""playing a game"" and here is the code that I implemented: bot.on('ready', () => { console.log('Client is online!'); bot.user.setActivity('osu!'); Th ...

Creating a pop-up modal in an Angular2 application that incorporates a child

Can anyone help me figure out how to use Ng Bootstrap Modal with a child component as the modal body? I'm unsure of the best way to achieve this... export class ParentComponent { @ViewChild("modal") private engineModal: TemplateRef<any>; ...

Exclude certain packages from being processed in webpack

After setting up my webpack configuration, everything was running smoothly with the specified packages in the package.json: { "peerDependencies": { "react": "16.13.1", "react-dom": "16.13.1", ...

The consistency of values remains constant throughout all Ajax requests

I am presenting the code snippet below: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title>Document</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" ...

Apply a border to the navbar when it hovers over a selected element

export const NavBar = () => { return <div className="navbar">this is navbar</div>; }; const Content = () => { return ( <div className="main"> <div className="background"> some content </div> ...

Using jQuery setTimeout within a forEach loop

Currently, I am fetching an array of messages using 'getJSON method. My intention is to display each message for 3 seconds before moving on to the next one. The process involves loading an HTML file and applying a CSS class to each message. However, m ...

Merging Technology: Integrating Maps into Hybrid Applications

Currently, I am developing a mobile application using React-Native with a main focus on: Map Integration: Partial Success - I have successfully implemented all features mentioned in this link. The remaining task is to display live routing based on curren ...

Refreshing the page causes Firebase authentication to vanish

My React app integrates Firebase authentication. However, I am facing an issue where the firebase:authUser is stored in localStorage upon successful login, but gets cleared on every page refresh resulting in a lost session. Surprisingly, browsing through o ...

What is the best way to bring the global stylesheet into a Vue component?

Embarking on my first VueJS project, I decided to create a global stylesheet to maintain consistent styles across different components. After installing the SCSS loader and setting up my stylesheets, I encountered an issue. $mainFont: 'PoppinsRegular, ...

Using an AJAX post request to retrieve the HTML content

I'm grappling with an AJAX function and a processor.php script. Here's the code snippet: $.ajax({ url: "processor.php", type:"POST", data: { 'id' : "itemid, 'itemname' : itemname, 'itemdesc' : itemdesc" ...

What causes the JavaScript code to output the number 3?

What is the reason behind the output a == 3 in this code snippet? var x = "abc"; var y = 3; var z = "xyz"; var a = x && y || z; Here is the link to interact with the code: http://jsfiddle.net/thinkingmedia/qBZAL/ One might assume that a == true ...

Error encountered with Protractor: 'TypeError: undefined is not a function'

I have explored various discussions on this particular error code. Nevertheless, I am finding it challenging to come across any solutions that are effective (or perhaps I am just not understanding them). While constructing a Protractor test for a webpage, ...

Elements that are added dynamically will not inherit the correct CSS styles, requiring JavaScript to style them properly

My <ul> element dynamically adds <li> elements, and I am attempting to make the first <li> wider at 63% while the others are at 60%. However, the first one is only getting a width of 60%. Any thoughts on why this might be happening? I ne ...

Creating a fetcher that seamlessly functions on both the server and client within Nextjs 13 - the ultimate guide!

My Nextjs 13 frontend (app router) interacts with a Laravel-powered backend through an api. To handle authentication in the api, I am utilizing Laravel Sanctum as suggested by Laravel for SPAs. This involves setting two cookies (a session and a CSRF token) ...