Displaying all notifications while using parameters in TypeScript

I am trying to display all of my notifications in HTML. The value is returned in res = response.json();, but my website only shows one notification, similar to the example in https://i.sstatic.net/ECbyx.png Let's start with this code:

  public eventsbyserial(id: string): Observable<Notifications> {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    let urlSearchParams = new URLSearchParams();
    urlSearchParams.append('serial_device', id);
    urlSearchParams.append('token', this.auth.getCurrentUser().token);
    let body = urlSearchParams.toString();

    return this.http.post(Api.getUrl(Api.URLS.eventsbyserial), body, {
      headers: headers
    })
      .map((response: Response) => {
        let res = response.json();
        console.log(res) // this shows me all notifications
        if (res.StatusCode === 0) {
          return new Notifications(res.StatusDescription[0]);
        } else if (res.StatusCode === 1) {
          this.auth.logout();
        } else {
          return new Notifications(null);
        }
      });
  }

Next, we have this code snippet:

 notificcationserial: Notifications[]=[];
  notif: Notifications;
     getalleventsserial() {
        this.activatedRoute.params.subscribe(
          params => {
            this.ns.eventsbyserial(params['id']).subscribe(
              notificcationserial => {
                this.notif = notificcationserial;
                console.log(this.notif) // Only one notification is displayed here
              }
            );
          }
        );
      }

In the HTML:

  <table *ngFor="let item of notificcationserial ">
          <tr >
              <td> {{item.alarmnumber}}</td>
              <td> {{item.acted}}</td>       
          </tr>
   </table>

I'm facing an issue where only one notification is being displayed on my site. Any ideas for a solution?

UPDATE:

   if (res.StatusCode === 0) {
              return new Notifications(res.StatusDescription); 

The result shows as undefined, similar to the image shown here: https://i.sstatic.net/ED17l.png

Answer №1

Make sure to only return the first entry in your array and ensure that StatusDescription is not wrapped inside an array in Notifications.

[...]
    if (res.StatusCode === 0) {
      return new Notifications(res.StatusDescription[0]);
[...]

Consider approaching it this way.

public eventsbyserial(id: string): Observable<StatusDescription> {

[...]
    if (res.StatusCode === 0) {
      return res.StatusDescription;
[...]


notif: StatusDescription;
   getalleventsserial() {
      this.activatedRoute.params.subscribe(
        params => {
          this.ns.eventsbyserial(params['id']).subscribe(
            notificcationserial => {
              this.notif = notificcationserial;
              console.log(this.notif) // supposed to show 2 rows according to your example
            }
          );
        }
     );
   }

Ensure your HTML code looks like this

  <table *ngFor="let item of notif">
          <tr >
              <td> {{item.alarmnumber}}</td>
              <td> {{item.acted}}</td>       
          </tr>
  </table>

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

The functionality of MaterializeCSS modals seems to be experiencing issues within an Angular2 (webpack) application

My goal is to display modals with a modal-trigger without it automatically popping up during application initialization. However, every time I start my application, the modal pops up instantly. Below is the code snippet from my component .ts file: import ...

Tips for changing the color of an MUI 5 checkbox and label when hovering

I am looking to create a checkbox enclosed in a wrapper with a label. The goal is to change the color of everything inside the wrapper when it is hovered over. Here is an example image: https://i.sstatic.net/T3OU5.png Below is the code I have attempted: ...

Do Angular routes need to have distinct prefixes?

I have defined two routes. /apples---> AppleComponent, /apples/:id ---> AppleDetailComponent, When I visit /apples/111, it will first go into AppleComponent and then into AppleDetailComponent. What steps should I take to make it only match /appl ...

React | What could be preventing the defaultValue of the input from updating?

I am working with a stateful component that makes a CEP promise to fetch data from post offices. This data is retrieved when the Zip input contains 9 characters - 8 numbers and a '-' - and returns an object with the desired information. Below is ...

Issue encountered while attempting to start a project using Ionic

After cloning a repository using the git clone command and running npm install, I encountered a message with warnings about vulnerabilities: npm WARN deprecated" and at the end it says "55 vulnerabilities (3 low, 12 moderate, 36 high, 4 critical) To addres ...

Navigating through pages in your IONIC 3 application: A guide to routing

I have been working on an Ionic 3 project and currently using NavController for page navigation. For example: this.navCtrl.push(DetailsPage); However, I now need to switch to Angular routing. I came across a similar query regarding Ionic 2 in this link. ...

What is the best way to extract data from an [object Object] and store it in an Array or access its values in Angular?

My Angular code is written in the component.ts file. I am fetching data from a backend API and using console.log to display the data. getInfo() { const params = []; params.push({code: 'Code', name: 'ty_PSD'}); params ...

Is it possible to nullify an object and utilize nullish coalescing for handling potentially undefined constants?

In my development work with React, I often utilize a props object structured like this: const props: { id: number, name?: string} = { id: 1 }; // 'name' property not defined const { id, name } = props; // the 'name' constant is now fore ...

Determining the Clicked Button in ReactJS

I need help with a simple coding requirement that involves detecting which button is clicked. Below is the code snippet: import React, { useState } from 'react' const App = () => { const data = [ ['Hotel 1A', ['A']], ...

Is it possible to establish a specific many-to-many relationship using Prisma?

In the Prisma documentation, it states that the set function can be used to override the value of a relation. const user = await prisma.user.update({ where: { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="73121f ...

Encountering an error while trying to run ng serve following ng build

Currently working on my initial Angular application, I am in the process of setting up an existing Angular app on my local machine. Encountered the following error message when running ng serve ERROR in src/app/common-componets/directives/dropFile/d ...

Elevate your software from Angular 13 to 14 for Improved Routing Performance

Since updating to version 14, I've encountered the following error: An error occurred due to an invalid configuration of route 'map/operator/': a componentless route without children or loadChildren cannot have a named outlet set Below is ...

Subject fails to subscribe to the change

There are two components in my project that share a common service. shared.service.ts // ..... skipping top level codes private pickAnalysisForBubble = new Subject<any>(); analysisForBubble$ = this.pickAnalysisForBubble.asObservable(); mapTo ...

Angular2: Exploring the Differences Between Observable.fromEvent and Button Click

As I work with my code, I have noticed that I am using both <button (click)="callsomefucntion" /> and Observable.fromEvent<MouseEvent>(button.nativeElement.'click') interchangeably. I am curious to understand the distinction between ...

Detecting URL changes on new windows in Angular Typescript: How to do it?

I am currently working with the updated version of Angular 6. My task involves opening a new browser window based on user input, which includes a specific return URL. After the return URL is fully loaded, I need to access and extract a particular element f ...

What strategies can I use to steer clear of the pyramid of doom when using chains in fp-ts?

There are times when I encounter a scenario where I must perform multiple operations in sequence. If each operation relies solely on data from the previous step, then it's simple with something like pipe(startingData, TE.chain(op1), TE.chain(op2), TE. ...

Angular static dropdown option

<input [formControl]="twitterHandle" id="twitterHandle" placeholder="twitterHandle"> Fetching the input value from the Twitter handle input field using the following code: twitterHandle = new FormControl(); this.twitterHandle.value; Similarly, if ...

Achieve HTTPS with angular-cli when running ng serve

It seems like the code snippet below is not working as expected. ng serve --ssl true --ssl-key <key-path> --ssl-cert <cert-path> Even when creating the Certificate and key by placing them in the default ssl directory, there is still no effect ...

Tailwind component library - personalize color schemes for your project's design

I recently created a component library using Tailwind and React, and I've utilized Rollup for building the distribution files. In my tailwind.config.js file, you'll find the following color declarations: const colors = require('tailwindcss/c ...

Separate the label and content sections in an Angular Material vertical stepper

https://i.sstatic.net/S1gIH.jpg After applying the following CSS: mat-step-header{ display: flex ; justify-content: flex-end ; } I am attempting to make this stepper function properly. I have implemented Angular Material design for a vertical stepp ...