Tips for concealing backend data in Angular2 under the conditions where the name is designated as anonymous and the nested array is empty

I'm dealing with an array of data fetched from the backend and I need to meet the following requirements:

  1. If the user's name, "from_user_name", is Anonymus, then the contents must be hidden.
  2. Hide the messages if the array is empty.

Can someone assist me in resolving these 2 conditions?

HTML:

<ul>
    <li *ngFor="let message of activeMessages" (click)="showMessage(message)" [class.activeShow]="message.id == message_id">
      <span>{{message.updated_at  | date:'dd.MM.yyyy'}}</span>
      <img style="width: 40px;" [src]="message.from_user_image || '../assets/images/msg.png'"/>
      <p style="padding-top: 16px;display: inline;">{{message.from_user_name}}</p>
      <p style="padding-top: 10px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;"><b>{{message.text}}</b></p>
    </li>
  </ul>

TS:

loadMessages() {
    this.service
          .getMessages()
          .subscribe(
            data => {
              this.messagesdata = data;
              this.activeMessages = data.filter(msg => msg.active == true);
              this.closedMessages = data.filter(msg => msg.active == false);
              if (this.activeMessages.length > 0) {
                if(!this.message_show) {
                  var test = this.message_show = this.activeMessages[0];
                  this.message = true;
                  this.message_id = this.activeMessages[0].id;
                }
                console.log(this.activeMessages);
              }              
            },error => {});
  }

Console: https://i.sstatic.net/cDIe6.png

Answer №1

this behavior should ideally be screened at the backend, however, in a different scenario, the following code can be utilized:

fetchLatestMessages() {
    this.messageService
      .getAllMessages()
      .subscribe(
        result => this.messages = result.filter(message => message.active && message.from_user_name !== 'Anonymus' && message.body.length > 0)
}

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

Wondering how to implement HubSpot Conversations SDK in a Typescript/Angular application?

Recently, I came across some useful javascript code on this website window.HubSpotConversations.widget.load(); window.HubSpotConversations.widget.refresh(); window.HubSpotConversations.widget.open(); window.HubSpotConversations.widget.close(); Now, I am l ...

Angular 2 web SQL definitions

Currently, I am developing an electron app with Angular 4 and need to integrate a database. My preference is to utilize websql, but I am facing challenges importing the necessary typings. Upon adding @types/websql to my project and writing the code: cons ...

Encountering a bug in Angular 10 while attempting to assign a value from

I am having trouble updating the role of a user. In my database, I have a user table and a role table with a ManyToMany relation. I can retrieve all the values and even the correct selected value, but I am encountering issues when trying to update it. Her ...

Utilizing Generic Types in React TypeScript Functional Components

I'm currently developing a TypeScript React component that includes generic type props, so I define the React component as: export interface MyCompProps<T> { items: T[]; labelFunction: (T) => string; iconFunction: (T) => JSX.Element; ...

Errors that occur when parsing templates in Angular 2

I'm encountering a template parse error with my Angular 2 component using the following template: <div *ngIf="chapter == 1"> <p><h4><br><b>Exercise</b>: Get the Groceries starting point<br></h4 ...

How to import an HTML file using TypeScript

I need to load an html file located in the same directory as the typescript file and return it from the function. public ...(... ) : angular.IHttpPromise<string> { ... return $http({ method: 'GET', url: &apos ...

Can an Observable be created that emits an array produced by awaiting asynchronous methods?

I've encountered an issue with the following method: get fileResults$(): Observable<File[]> { return this.ngRedux.select<ICommunicationState>('communication').pipe(map(newState => { const files: File[] = []; ...

Obtaining the attribute value from a custom tag in Angular: A comprehensive guide

I am currently working on creating a customized password component in Angular5. I am having difficulty obtaining the minimum and maximum attribute values required to validate the password. I attempted to retrieve the values using JavaScript's getAttr ...

What is the best way to define the type of an object when the Key is already known?

If I have the code snippet below, how can I properly define the data object type based on the known value of data.type? In this scenario, I aim to assign a specific type to data when its type property is either "sms" or "email" const payload = '{&quo ...

Issue occurred with Firebase geoFire setting: unable to access properties of undefined when reading 'pieceNum_'

Recently, I decided to update my old Ionic Angular app and upgraded the firebase module to version 9.23.0 along with the geofire module to version 6.0.0. However, upon calling the set function on geoFire with an id and an array of coordinates, I encountere ...

update the data source of the material table inside the subscription

Seeking guidance for updating a MatTable datasource within an Angular application. The current Typescript code involves fetching data from an API using AdminService, iterating over the results to make additional API calls for more information about a fleet ...

Acquire data through Reactive Form input

Struggling to populate my entity data in a reactive form. Data retrieval is successful, but unsure about the ideal method and timing for filling out the form with these values. Here's the structure of my form: import { Component, OnInit, Input } fr ...

When the first argument is missing, using a recursive constraint default can result in the incorrect inference of the second argument, especially when both arguments share the same generic

Currently, I am developing a TypeScript implementation of a recursive binary search tree (BST) data structure using generic constraints. In order to establish a default for the recursive generic variable T without directly using it in the default declarati ...

Is there an easier method to utilize ES6's property shorthand when passing an object in TypeScript, without needing to prefix arguments with interface names?

When working with JavaScript, I often find myself writing functions like the one below to utilize ES6's property shorthand feature: function exampleFunction({param1, param2}) { console.log(param1 + " " + param2); } //Usage: const param1 = "param1" ...

Typescript declaration specifies the return type of function properties

I am currently working on fixing the Typescript declaration for youtube-dl-exec. This library has a default export that is a function with properties. Essentially, the default export returns a promise, but alternatively, you can use the exec() method which ...

The Angular router seems to be refusing to show my component

My Angular 2 App includes a Module called InformationPagesModule that contains two lazy load components (Info1 Component and Info2 Component). I would like these components to load when accessing the following routes in the browser: http://localhost:4200/ ...

Error encountered during the build process in Angular microfrontends/multirepos using Webpack external module

I have developed an Angular project to integrate a microfrontend with another running Angular project. I have successfully imported the module into my application using webpack.config.js. Everything works fine on my local environment, but I encounter issue ...

Trouble encountered with uploading files using Multer

I am facing an issue with uploading images on a website that is built using React. The problem seems to be related to the backend Node.js code. Code: const multer = require("multer"); // Check if the directory exists, if not, create it const di ...

Using Typescript to assign a custom object to any object is a powerful feature

I am attempting to organize table data by utilizing the code found at https://github.com/chuvikovd/multi-column-sort. However, I am unsure of how to pass a custom object to the SortArray[T] object. The structure of my custom object is as follows: const ob ...

Enhancing Google analytics integration with Continuous Integration (CI) in Angular 9

Currently, I am working on an app that is being developed on circleCI. Since updating Angular from version 7 to 9, there has been a prompt to install the CLI on circleCI. Google’s Privacy Policy at https://policies.google.com/privacy? For more details ...