Utilizing Angular Ionic to Extract and Showcase Information Derived from Other Data

I am attempting to show a date that corresponds to a specific order status. However, the current output is incorrect as it displays all dates for each order instead of just the relevant one.

https://i.sstatic.net/FRy0z.png

Below is my .ts code:

constructor(private dataService: DataService, private http: HttpClient) {
  this.data = '';
  this.error = '';
 }

public statuses = [];
public dates = [];

private prepareDataRequest(): Observable<any> {  
  const dataUrl = ''; 
  return this.http.get(dataUrl);
}

ionViewWillEnter() {
  this.prepareDataRequest().subscribe(
    data => {
      this.statuses = data.output.Result.partsOrderTrackingListSequence
        .map(item => {
          if (item.status && item.status !== '') {
            return item.status;
          } else {
            return '-';
          }
        });
        this.dates = data.output.Result.partsOrderTrackingListSequence
        .map(item => {

          if (item.date && item.date !== '') {
            return item.date;
          } else {
            return '-';
          }
        });
    },
    err => {
      this.error = `An error occurred, the data could not be retrieved: Status: ${err.status}, Message: ${err.statusText}`;
    }
  );
}

My page.html code:

<ng-container *ngIf="!error; else errorContent">
    <p *ngFor="let status of statuses let date of dates">
      {{ status }} - {{date}}
    </p>
  </ng-container>
  <ng-template #errorContent>
    <p>
      <span style="color: red;">{{error}}</span>
    </p>
  </ng-template>

If anyone can provide tutorials or guides on parsing and displaying JSON data in Angular Ionic pages, as well as modifying date display formats, I would greatly appreciate it. I am new to Angular and Typescript and have had difficulty finding helpful resources on these topics.

Answer №1

You must make changes to your ionViewWillEnter() method

OrderList= [];
ionViewWillEnter() {
  // Fetch the data
  this.prepareDataRequest().subscribe(
    data => {
      // Populates OrderList with data from Result.partsOrderTrackingListSequence array and prints it
      this.OrderList = data.output.Result.partsOrderTrackingListSequence


    },
    err => {
      // Set error information for display in template
      this.error = `An error occurred, the data could not be retrieved: Status: ${err.status}, Message: ${err.statusText}`;
    }
  );
}

In your HTML file

<ng-container *ngIf=""!error; else errorContent"">
    <p *ngFor=""let order of OrderList;"">
      {{ order.status }} - {{order.dates}}
    </p>
  </ng-container>
  <ng-template #errorContent>
    <p>
      <span style=""color: red;"">{{error}}</span>
    </p>
  </ng-template>

Answer №2

Consolidate the values from the observable into a single array-like structure instead of multiple arrays. Utilize this array for data binding in the template with valid values.

Template file:

// Array to store order values.
orders= [];
ionViewWillEnter() {
  // Fetching the data
  this.prepareDataRequest().subscribe(
    data => {
      // Consolidating data into a single Array and displaying it 
      this.orders = data.output.Result.partsOrderTrackingListSequence;
    },
    err => {
      // Setting up error information to be shown in the template
      this.error = `An error occurred, the data could not be retrieved: Status: ${err.status}, Message: ${err.statusText}`;
    }
  );
}

Template file

<ng-container *ngIf="!error; else errorContent">
    <p *ngFor="let order of orders">
      {{ order?.status || '-' }} - {{order?.date || '' }}
    </p>
  </ng-container>
  <ng-template #errorContent>
    <p>
      <span style="color: red;">{{error}}</span>
    </p>
  </ng-template>

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

Enhance your Next.js routing by appending to a slug/url using the <Link> component

In my Next.js project, I have organized my files in a folder-based structure like this: /dashboard/[appid]/users/[userid]/user_info.tsx When using href={"user_info"} with the built-in Next.js component on a user page, I expect the URL to dynamic ...

Setting a default value for a data type within Typescript

My goal is to set default values for all properties in my custom type if they are not defined. This is what I have done: // custom type with optional properties type MyType = { // an example property: str?: string } // with numerous properties, assign ...

Using Typescript to specify the parameter type of a function as a generic function

After creating a function called compose, it looks like this: const composeTyped = <T, U, R>(f: (x: T) => U, g: (y: U) => R) => (x: T) => g(f(x)); It appears to me that both functions f and g fall under the type fGeneric, which is define ...

Encountering a Compilation Issue in Angular 4

After executing npm install bootstrap@next in my new Angular project, I encountered a compilation error. As a beginner with Angular, I'm seeking assistance on this issue. Compilation Error: ./node_modules/ansi-html/index.js Module build failed: ...

Angular 2 Error: AOT issue with base64 function not recognized

Currently, I'm attempting to compile my project using AOT. When I execute the command ngc -p tsconfig-aot.json Initially, it creates an aot folder with ngFactroy. However, when I modify the main ts file (as specified in the Angular documentation) to ...

Show an Angular Mat Card beneath the Input Field and position it on top of all other div elements

I am designing a signup page and I need to include a material card below the password field with checkboxes for password requirements. The challenge is that when the card appears, it pushes down all other elements such as the sign-up button. I want the ca ...

Unable to get md-virtual-repeat to work within md-select?

Attempting to use md-select to showcase a large amount of data is causing the browser to freeze upon opening. To address this, I tried implementing md-virtual repeat within md-select for improved performance. However, the code doesn't seem to be funct ...

Translate language in an Angular file using TypeScript

const typeArray= [ { id: 'PARENT', name: '{{ appConstants.type.PARENT | translate }}' }]; What is the best way to incorporate translations when declaring an array in a TypeScript file? ...

Tips for integrating Pico CSS into the overall scss stylesheet of your Angular project

After setting up a fresh Angular 17 project using SCSS for the stylesheet format, I decided to integrate Pico CSS into my development. However, implementing it according to the instructions in the Pico CSS documentation led to an error: ✘ [ERROR] Can&apo ...

An unexpected error has occurred in Angular 2 while referencing the service proxy with code asd:18. The error message is: (SystemJS) Unexpected token < SyntaxError: Unexpected token

Forgive me for asking what may seem like a silly question. I am a newcomer to Angular 2 and encountering some problems with the API that my app is utilizing. The consumed Web API is located within the following folder structure: - src - app - Regist ...

Discover the process of selecting an item from a list and viewing it on a separate page with the help of AngularJS and Ionic technology

I am struggling with creating a list of items that, when clicked, should take me to the corresponding post. Despite trying to use ng-click in the header, I suspect there is an issue with the route not functioning properly. As part of my testing process, I ...

Using an Object as a parameter in a Typescript function

I am currently working on an Angular component that includes a function. Within this function, I need to pass an Object as a parameter and invoke the function with these parameters. It has been some time since I last worked with Angular, where "any" was ty ...

Navigating within a nested view using Angular's UI-Router

I've encountered a puzzling issue that I've been grappling with for the past three days. It seems like a straightforward problem, but for some reason, it's causing me a lot of trouble. The main parent view in my code contains two child view ...

The inability to destructure the 'store' property from the 'useReduxContext(...)' because of its null value

I am currently using NextJs 13 along with redux toolkit. Whenever I run the npm run build command, I encounter this error: "Cannot destructure property 'store' of 'useReduxContext(...)' as it is null." I suspect that the issue lies wi ...

What is the correct way to implement Vue.use() with TypeScript?

I am trying to incorporate the Vuetify plugin into my TypeScript project. The documentation (available at this link) suggests using Vue.use(), but in TypeScript, I encounter the following error: "error TS2345: Argument of type '{}' is not assign ...

Working with nested arrays in TypeScript and how to push values onto them

I am facing some challenges with nested array behavior in TypeScript. I am looking for a way to define a single type that can handle arrays of unknown depth. Let me illustrate my issue: type PossiblyNested = Array<number> | Array<Array<number& ...

Angular 2 does not include Bootstrap CSS by default

Found this helpful tip at https://angular.io/docs/ts/latest/guide/forms.html Time to include the stylesheet you need. Go to your application's root folder in the terminal and run this command: npm install bootstrap --save In index.html, make sure ...

Customizing the colors of Angular Material themes

Currently, I am looking to completely change the theme of my angular 8 application. Within a scss file, I have the following code: @import '~@angular/material/theming'; // Plus imports for other components in your app. // Include the common st ...

Utilizing Protractor's advanced filtering techniques to pinpoint the desired row

I am trying to filter out the specific row that contains particular text within its cells. This is my existing code: private selectTargetLicense(licenseName: string) { return new Promise((resolve => { element.all(by.tagName('clr-dg-tab ...

Having Trouble with Angular2: Nesting a Child Component?

Working with angular 2 has been a fun experience for me over the past few days. I've been attempting to insert a child selector into a parent template, but it seems more challenging than I expected. Every time I try, I encounter the following error: ...