Guidelines for sorting a dataset according to the current UserID using angular2

Hello, I am working with a dataset where I need to filter the data based on my userID and display only that specific information in a list. Can someone assist me with this? TS:

getDicomList() {
    this.service.getDicomList(params)
      .subscribe((res) => {
        this.dicomLists = res.Body.Data.dicomList;
        console.log(this.dicomLists, "shghds")
        let ids = this.dicomLists.map(item => item.CreatedBy);
       let filteredData = this.dicomLists.filter(item => ids.indexOf(item.CreatedBy) === -1);
      })

      I need to compare my userID with item.CreatedBy.

Console:

(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {StudyInstanceUID: "999.999.1.19941016.83000", StudyID: "ACC99", SeriesNumber: "2", AcquisitionNumber: "0", InstanceNumber: "101", …}
1: ............(content truncated for brevity)............
9: {StudyInstanceUID: "1.3.6.1.4.1.18047.1.11.10021841473447061672", StudyID: "", SeriesNumber: "4", AcquisitionNumber: "1", InstanceNumber: "49", …}
length: 10
__proto__: Array(0)

Answer №1

Here is an example of how it can be done:

fetchData() {
    this.service.fetchData(params)
      .subscribe((result) => {
        this.dataList = result.body.content;
        console.log(this.dataList, "abc123")
        //let ids = this.dataList.map(item => item.ID);
       let filteredData = this.dataList.filter(item => this.currentUserId == item.CreatorID);
      })

Answer №2

A simple tweak is all that's required.

fetchDicomData() {
    this.service.fetchDicomData(params)
      .subscribe((result) => {
        this.dicomInfo = result.Body.Content.dicomData;

       let filteredResults = this.dicomInfo.filter(entry => entry.Author === this.userId);
      })

Answer №3

Below is some code that you can test out:

let filteredData = this.dicomLists.filter(item => (this.userId == item.CreatedBy));

Answer №4

It is crucial to always include a null check

        fetchDicomData() {
        this.dicomService.fetchDicomData(params)
          .subscribe((response) => {
                 this.dicomLists = [];
                 // Make sure to perform a null check to avoid errors
                 if(response.body && response.body.Data 
                      && response.body.Data.dicomList
                      && response.body.Data.dicomList.length){
                   this.dicomLists = response.Body.Data.dicomList;
                 }
           return this.dicomLists.filter(item => this.userId == item.CreatedBy);
          })

Answer №5

When calling this.service.getDicomList(params), the response is subscribed to and the data is stored in this.dicomLists. The code then filters out items in dicomLists where the CreatedBy property matches the userId. This simplifies the filtering process compared to the previous implementation.

JUST LIKE THAT

this.service.getDicomList(params).subscribe((res) => {
    this.dicomLists = res.Body.Data.dicomList;
    this.dicomLists.filter(item => item.CreatedBy === this.userId);
})

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

What could be causing this TypeError to appear in my Angular unit testing?

this.columnDefs.forEach((columnDef) => { columnDef.floatingFilter = this.hasFloatingFilter; }); this.gridApi.setColumnDefs(this.columnDefs); ERROR: 'ERROR', TypeError: this.gridApi.setColumnDefs is not a function TypeError: this.gridApi.set ...

Leveraging ts-jest in conjunction with create-react-app

Having trouble getting accurate coverage reports when running tests with the --coverage flag using create-react-app and react-scripts-ts for TypeScript. Is there a way to integrate ts-jest for correct coverage reports? Here's my jest configuration in ...

The 'onRemove' property is not found within this type

I am looking to add a remove button for drag and drop items, but when I try to save the code, I get a compilation error. The error message reads: "Property 'onRemove' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttribute ...

The div is not showing the image as expected

Having some trouble creating a slideshow within my angular application. Struggling to get the images to display in the html code. To tackle this, I decided to create a separate component specifically for the slideshow (carousel.component). In the main app ...

Ionic - interactive search feature

Is there a way to customize the behavior of a search bar so that it only reacts to taps or clicks without triggering the keyboard? I want to replicate the functionality of Google Maps where the user tap on the bar a new view or modal appears with a ...

Updating an array in a single line of code in Javascript can be achieved

Can the code below be optimized? const item: any; // New data const index: number = basketModel.data.coupons.findIndex( (x: any) => x.couponId === item.couponId ); if (index === -1) { // If new item, push it to array ...

Frontend receiving data from an unexpected localhost address even with proxy settings in place

My React frontend application has a proxy configured in the package.json file to connect to my Flask backend running on http://localhost:2371. However, when trying to fetch data from the backend using fetch("/members"), the frontend is unexpectedly fetchin ...

Sending information to the styles feature in Angular 2

Is there a way to transfer data from an Angular tag to the styles in the @Component? Take a look at my component: import { Component, Input } from '@angular/core'; @Component({ selector: 'icon', template: `<svg class="icon"> ...

Material-UI Slide component is encountering an issue where it is unable to access the style property of an undefined variable

Recently, I incorporated Material-UI Slide into my project and I'm curious about why the code functions correctly when written in this manner: {selectedItem && selectedItem.modal && selectedItem.modal.body ? ( selectedItem.modal.body.map((section ...

Simplify if statements by eliminating repetition

I have been tasked with refactoring the code below and I have already done so (check the image for reference). However, my supervisor is still not satisfied with the changes, LOL. const { appTargetId, appUserTargetId, appUserId } = buildIndexKeys(input); ...

Issue: "A 'reflect-metadata shim is needed' error occurs during the transition to Webpack 2"

My team and I are facing a challenge as we try to upgrade our code base to Webpack 2. Currently, we're encountering two stubborn errors: 'Uncaught reflect-metadata shim is required when using class decorators' and 'Cannot read property ...

Error: The utilization of the life cycle interface mandates the implementation of type checking

Currently, I am in the process of translating my typescript project to Webpack 2. While one project transitioned smoothly, I encountered an error with the other project... Error: use-life-cycle-interface necessitates type checking After conducting a br ...

Error: Unexpected top-level property "import/order" in ESLINT configuration

I'm in the process of setting up a guideline to include one blank line between internal and external imports. .eslintrc.json: { "parser": "@typescript-eslint/parser", "env": { "es6": true, " ...

Error in Angular FormArray: Unable to access the 'push' property because it is undefined

Currently, I am working with a form that is divided into 3 subcomponents, each containing 3 form groups. The 3rd group contains a FormArray which will store FormControls representing true/false values for each result retrieved from an API call. Initially, ...

The angular datepicker functionality seems to be malfunctioning

unique-example encountering this error message: error TS2307: Cannot find module 'mydatepicker' also encountering a compile time error at this line: import { MyDatePickerModule } from 'mydatepicker'; report.module.ts : import ...

In Typescript, which kind of event is suitable for MouseEvent<HTMLDivElement>?

My goal is to close the modal when clicking outside the div element. Take a look at my code below. // The onClose function is a setState(false) function. import { useRef, useEffect } from 'hooks' import { MouseEvent } from 'react' imp ...

What is the process for listening to custom events in Angular 4 components that have been loaded using routing?

In the app.component.html file <li routerLinkActive="active current"> <a [routerLink]="['/stats']"> Cluster stats </a> </li> When we route to the DisplayAllStatsComponent, how can we ...

Implement method functionality within TypeScript interfaces

I've encountered a scenario where I have an interface that will be utilized by multiple classes: interface I { readonly id: string; process(): void; } My objective is to pass the id through a constructor like so: class A implements I {...} let a: ...

Replacing a push operation in JavaScript with a splice operation

Upon entering a screen, 5 promises are automatically loaded using promise.all. The issue is that they are executed in a random order, and within each function, I use a push to store the information. The problem arises when I need to change the push to a s ...

Eliminating an item from an array with the help of React hooks (useState)

I am facing an issue with removing an object from an array without using the "this" keyword. My attempt with updateList(list.slice(list.indexOf(e.target.name, 1))) is only keeping the last item in the array after removal, which is not the desired outcome. ...