TS2339: The function 'slice' is not found on the data type 'WritableSignal<Product[]>'

Currently, I am facing a challenge in my Angular 10.1.0 project while attempting to implement pagination by slicing my data array. The issue arises with the error message

TS2339: Property 'slice' does not exist on type 'WritableSignal<Data[]>'
.

Here's a snippet from my component:

export class Component implements OnInit {
  data = signal<Data[]>([]);
  currentPage: number = 1;

  constructor(private httoService: HttpService) {}

  ngOnInit(): void {
    this.fetchData();
  }

  fetchData(): void {
    this.httpService.getData().subscribe((data) => {
      this.data.set(data);
    });
  }

  get paginatedData() {
    const start = (this.currentPage - 1) * 100;
    const end = start + 100;
    return this.data.slice(start, end);
  }

...
}

Details of my http.service.ts file:

export class HttpService {
  http = inject(HttpClient);
  private apiUrl = 'url'

  getProducts(): Observable<Data[]> {
    return this.http.get<Data[]>(this.apiUrl);
  }
}

I have attempted pre-processing the values before applying slice:

const dataArray = Array.from(this.data().values)
but it yielded 0 as the result.

Answer №1

When dealing with signals, you cannot directly use slice(). However, you can manipulate the signal's value by adding (). The easiest solution is as follows:

  get paginatedData() {
    const start = (this.currentPage - 1) * 100;
    const end = start + 100;
    return this.data().slice(start, end);
  }

If you prefer working with signals, you can replace the getter with a computed signal:

  paginatedData = computed(() => {
    const start = (this.currentPage - 1) * 100;
    const end = start + 100;
    return this.data().slice(start, end);
  }

This will turn your paginatedData into a signal, allowing you to utilize signal flow. You can easily incorporate it in your HTML (or any other location) by using

paginatedData()

Answer №2

To proceed, we have to carry out the signal, retrieve the array, and perform a slice operation

  obtain paginatedData() {
    const start = (this.currentPage - 1) * 100;
    const end = start + 100;
    return this.data().slice(start, end);  // <- modification made here!
  }

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 is the method for including word boundaries in a regex constructor?

export enum TOKENS { CLASS = 1, METHOD, FUNCTION, CONSTRUCTOR, INT, BOOLEAN, CHAR, VOID, VAR, STATIC, FIELD, LET, DO, IF, ELSE, WHILE, RETURN, TRUE, FALSE, NULL, THIS } setTokenPatterns() { let tokenString: s ...

Angular: How to Disable Checkbox

Within my table, there is a column that consists solely of checkboxes as values. Using a for loop, I have populated all values into the table. What I have accomplished so far is that when a checkbox is enabled, a message saying "hey" appears. However, if m ...

Issues with using hooks in a remote module in Webpack 5 module federation

I am attempting to create a dynamic system at runtime using Module Federation, a feature in webpack 5. Everything seems to be working well, but I encounter a multitude of 'invalid rule of hooks' errors when I add hooks to the 'producer' ...

Which programming language or technology utilizes the syntax <%VARIABLE%> and in what context is it employed?

First things first, I want to clarify that I'm not a developer, so this might be a simple question. Despite my research indicating that ASP typically uses this syntax, it's important to note that it is not the case here. I am currently delving i ...

The Kubernetes cluster unexpectedly closes down following a period of processing

My GCP cluster is hosting a NodeJS server. The server functions flawlessly when run locally, but mysteriously stops without any error messages when I attempt to send a post request to a specific route. This post request is supposed to trigger the sending o ...

Typescript ensures that the return type of a function is a key of an interface, which is determined based

I am attempting to enforce a specific return type from a function based on the key passed to it. For example, if the key is service1, then the correct return type should be Payloads['service1']. How can I accomplish this? interface Payloads { ...

Guide on how to retrieve the information stored in an object

I am experiencing an issue with my function that retrieves data from Firebase. I am able to read the objects, but I cannot access the properties within them. Whenever I try to parse the content, an error occurs. Here is the function in question: this ...

Stop the current HTTP request and initiate a new one asynchronously

My custom component showcases a detailed view of a selected building along with a list of its units (apartments). Below is the HTML code for this component: <div *ngIf="$building | async as building"> ... <div *ngIf="$buildingUnit ...

The identification of the field is not being transmitted by ng-select

Looking for help with Angular! I have an ng-select box where I can choose countries, and it's working fine when I select an option and submit - it submits the id as expected. However, when pre-populating the ng-select with data and submitting, it&apos ...

Extract the data from a deeply nested key within a JSON object

I'm currently working on a function that takes a key (specified as a string) and retrieves its corresponding values from a given JSON object. Here is the JSON data I am working with: [ { "some_key1": [ {"key": "va ...

A versatile tool for creating customizable components on the fly

I am looking to create a function within my service that generates dynamic components into a ViewChild reference... I attempted to do this by: public GenerateDynamicComponent(ComponentName: string, viewContainerRef: ViewContainerRef, data?: any) { sw ...

Is it possible to set a form control value as an object and display its label within an input field?

I am working on a basic form that includes an input field with autocomplete using Angular Material components. The issue I am facing is that when I select a value from the autocomplete box, the input field displays [Object object] as the value instead of t ...

Retrieve the value of a property within the same interface

Is there a way to access an interface prop value within the same interface declaration in order to dynamically set types? I am attempting something like this: export type MethodNames = "IsFallmanagerUpdateAllowed" | "UpdateStammFallmanager& ...

Issue with integrating jquery path into angular.json in JHipsterI'm facing a problem

Usually, it's quite simple to integrate SCSS styles and the jQuery path into an Angular project by adding them to the script:[] section. However: Upon inspecting the angular.js file created from jhipster, I noticed that the architect part is missing ...

Sending an image in the body of an HTTP request using Angular 7

I'm currently in the process of developing an Angular application that captures an image from a webcam every second and sends it to a REST API endpoint for analysis. To achieve this, I have implemented an interval observable that captures video from t ...

The embedded Twitter widget in the Angular 2+ app is visible only upon initial page load

After implementing the built-in function from Twitter docs into ngAfterViewInit function, my app works flawlessly. However, I encountered an issue where the widget disappears when switching routes. Here is the code that only functions on the initial page ...

Ways to stop dialog from disappearing in Reactjs

This code snippet demonstrates the implementation of a popup with buttons, where clicking the cancel button triggers a confirmation dialog. To make the popup disappear when clicked outside of it, the following event handling is employed: const popupRef = ...

What is causing checkboxes to malfunction within a form?

In my project, I have an array of objects representing pets: pets = [{key: 'dog', isChecked: true}, {key: 'hamster', isChecked: false}, {key: 'cat', isChecked: false}]; I want to display these objects as checkboxes. Here is ...

express-validator not providing any feedback from endpoint when integrated with TypeScript

I've been working on validating the response body for my endpoint, but I'm running into an issue where I'm not getting a response from that endpoint when using express-validator. I'm confident that I have followed the official documenta ...

I am looking to replicate a DOM element using Angular 4

I am interested in creating a clone of a DOM element. For example, if I have the following structure: <div> <p></p> <p></p> <p></p> <p></p> <button (click)="copy()"></button> & ...