Exploring the power of Angular 2 looping functionality

I am struggling to create a for loop to iterate through my array efficiently.

Below is the code snippet that I have and its functionality explained.

export class BookingService {
    private config: Object;
    public domainSettings: Object = {};
    constructor(
        private http: Http,
        private kioskservice: KioskService
    ) { }

    public getAllBookings() {
        return new Promise((resolve, reject) => {
            this.http
                .get(
                    `${this.kioskservice.getAPIUrl()}search/dashboard/${this.kioskservice.LocationGUID()}/?apikey=${this.kioskservice.getAPIKey()}&format=json&from=2018-04-17&until=2018-04-18&full=true`
                )
                .toPromise()
                .then(
                    res => {
                        this.config = res.json()
                        console.log(res.json());
                        resolve();
                    },
                    msg => {
                        throw new Error("Couldn't get all Bookings: " + msg);
                    }
                );
        });
    } 

The above code fetches an array from an HTTP request made to the API. Here is an example of the returned array :

(2) [{…}, {…}]
0
:
AssignedUserProfile
:
null
BookUserGuid
:
"221443aa-d3c7-4543-b858-6a8710904ff8"
BookingRequestGuid
:
null
BookingStates
:
[{…}]
Channel
:
"Private"
CheckCancelAllowed
:
{Result: "BookingCancelDateInPast", Price: null}
CheckEditAllowed
:
{Result: "BookingSaveTimeStartDateInPastError", Price: null}
Coordinates
:
null
Culture
:
"nl-NL"
Customer
:
{Guid: "f2791b53-9db0-4e86-99c0-8f25c1242e72", Reference: null, Name: "  test", DirectUrl: "https://dev.api.timeblockr.local/v2/userprofiles/f2791b53-9db0-4e86-99c0-8f25c1242e72"}
CustomerGuid
:
"f2791b53-9db0-4e86-99c0-8f25c1242e72"
...

I am looking to iterate through the arrays and extract the "TicketNumber" field to create a list of Ticket numbers instead of displaying the entire arrays. Can anyone provide guidance on how to achieve this using a for loop?

Answer №1

To start, it's important to either assign the array from the response to a variable or map it directly to the target array in the following manner:

this.ticketsArray = res.json.map(response => {
  return response.ticketNumber; // assuming 'ticketNumber' is the property name
}

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

Having difficulty executing the Cypress open command within a Next.js project that uses Typescript

I'm having trouble running cypress open in my Next.js project with Typescript. When I run the command, I encounter the following issues: % npm run cypress:open > [email protected] cypress:open > cypress open DevTools listening on ws: ...

Creating a Connection between Angular 4 and MySQL Database using PHP for Data Posting

After spending a few weeks searching for the answer to my question, I still haven't found what I'm looking for. I understand that Angular is a front-end framework and that I have freedom to choose any database and backend for my project. Current ...

Using TypeScript, one can easily employ a jQuery element within Vue's 'data' option

Is there a way to store a reference of a jQuery element in the Vue 'data' object without causing TypeScript errors? Any suggestions on how to resolve this issue? [EDIT] I managed to work around the TypeScript error by setting a non-existing jQu ...

Material UI TreeView: Organize and present node data with multiple columns in a tree structure

const treeItems = [ { id: 1, name: 'English', country: 'US', children: [ { id: 4, name: 'Spring', country: 'Uk', ...

Evaluate the Worth of a Property Established in a Subscription

Currently, I am using Jasmine for testing an Angular application and facing a challenge in testing the value of a property that is set within the subscribe call on an Observable within the component. To illustrate this point, I have created an example comp ...

Can the string literal type be implemented in an object interface?

My custom type is called Color, type Color = 'yellow' | 'red' | 'orange' In addition, I created an object with the interface named ColorSetting. interface ColorSetting { id: string yellow?: boolean red?: boolean orang ...

Does anyone know of a custom typeguard that enforces the presence of elements in an array?

I need help creating a custom type guard to determine if an array contains nullable or optional elements. I have defined a helper type called RequiredArray: type RequiredArray<A extends readonly any[]> = A extends [infer P, ...infer R] ? [Non ...

Collapsible list in Angular2 sidenav: ensuring only one sublist remains open

Presenting a functional sidenav demo with Angular 2, TypeScript, and Material Design components. The sidenav features a UL, with the Sites and Users anchors expanding to display their own sub-list. Check out the Plunker here Here is the HTML code for the ...

The module '@types/googlemaps/index.d.ts' cannot be found

I'm working on integrating the Google Maps API into my Angular project and ran into some issues. Here's what I did to install the necessary npm packages: npm install @agm/core --save-dev npm install @types/googlemaps --save-dev Next, I added th ...

Discover the solution to the issue of bookmarking a card on a page using react, typescript, and mui!

Whenever I try to favorite a card by clicking on its icon, all cards of the same type get bookmarked instead of just the one I clicked on. This is causing an issue where multiple cards are being favorited per page when I only want to bookmark individual on ...

Guide to effectively testing a function in Angular that outputs a promise

I am trying to unit test a function inside a component that calls a service method with 3 arguments and returns a promise. I have written the necessary code in Angular using karma jasmine testing framework. Would appreciate some feedback on my implementati ...

Utilizing dual functions within the onChange event handler in React

I have a situation where I need to pass a function from a parent component to a child component through the onChange event, as well as another function in the child component to update its own state. How can I achieve this? Parent export function Fruits() ...

Creating a Type that limits its keys to those from another Type, with the ability to assign new values to those keys. Attempting to introduce new keys should result in an

type Numbers = { a: number; b: number; f: number; }; type ValidateKeysWithDifferentTypes = SomeThingKeyOf<Numbers> & { a: string; b: Date; c: null; // Error occurs because 'c' is not found in Numbers type? // Error due ...

When trying to access a property in Typescript that may not exist on the object

Imagine having some data in JS like this example const obj = { // 'c' property should never be present a: 1, b: 2, } const keys = ['a', 'b', 'c'] // always contains 'a', 'b', or 'c' ...

What exactly does Type refer to in Angular 2?

I keep encountering the Type keyword in various parts of the documentation. For instance, in this link, it mentions that the ComponentRef has a property called componentType which is of type Type<any>. Upon further investigation, I stumbled upon this ...

Why am I encountering the 'nonexistent type' error in my Vue 3 project that uses Typescript and Vuelidate?

Seeking assistance with a Vue 3 and Vuelidate issue. I followed the configuration guide provided at . <script lang="ts"> import { required, minLength, maxLength, numeric } from '@vuelidate/validators' import useVuelidate from &apo ...

Navigating the world of NestJs and TypeScript with the `mongoose-delete` plugin: a comprehensive guide

I am currently utilizing Mongoose within the NestJs library and I want to incorporate the mongoose-delete plugin into all of my schemas. However, I am unsure of how to implement it with nestJS and Typescript. After installing both the mongoose-delete and ...

Display the date format based on the computer's settings using Angular 2

When I visited http://momentjs.com/docs/#/displaying/format/, I noticed the "Localized formats" options like L. I thought that these settings would change the date display from mm/dd/yyyy to dd/mm/yyyy based on the user's browser or computer locale s ...

Passing data between two Angular directives using EventEmitter

Looking to share a variable between two directives in Angular 7 Check out the updated code here: https://stackblitz.com/edit/angular-ct49bn The issue arises when selecting a customer from the list, as the emitter fails to communicate with the other direc ...

Effectively Monitoring Angular Router Link Status

Is anyone else facing an issue with router link active not working correctly when navigating to a route with a different ID? The class is applied on the first navigation, but not on subsequent navigations. Any solutions? This is my HTML file: <div clas ...