Failed to access element from the array using specified id

Seeking assistance with creating dynamic pages for each object in the boxArray file. I've developed a service called boxService to extract objects. While I am able to retrieve all elements successfully, encountering errors when attempting to extract individual objects using the getDifferentBox method:

TS2322: Type '<Observable null>;' is not assignable to type 'Observable&lt;IBoxModel&gt;'.<br/>Type 'null' is not assignable to type 'IBoxModel'.

TS2345: Argument of type 'IBoxModel | undefined' is not assignable to parameter of type 'IBoxModel'. Type 'undefined' is not assignable to type 'IBoxModel'.

Any insights on what could be going wrong? Appreciate your help.

boxService.ts

import { Injectable } from '@angular/core';
import {Observable, of} from "rxjs";
import {IBoxModel} from "../model/boxModel";
import {boxArray} from "../array/boxArray";

@Injectable({
 providedIn: 'root'
})

export class BoxService {

getBoxes():Observable<IBoxModel[]>{
 return of(boxArray)
}

getDifferentFox(id: string):Observable<IBoxModel> {
 return of<IBoxModel>(boxArray.find( value => value.id === + id ) )
}
}

boxArray.ts

import {IBoxModel} from "../model/boxModel";

export const boxArray: IBoxModel[] = [
{ id: 1,
  title: "Бокс номер 1",
  address: 0o1515,
}
{ id: 2,
  title: "Бокс номер 2",
  address: 0o1519,
}]

boxModel.ts

export interface IBoxModel {
  id: number;
  title: string;
  address: number;
}

Answer №1

According to derpirscher, there seems to be no issue with your discovery. However, you can adjust the data type of your function to solve the problem. This way, when there is no match, you will receive undefined and your method will handle it gracefully.

getDifferentFox(id: string): Observable<IBoxModel | undefined> {
   return of<IBoxModel>(boxArray.find((value) => value.id === +id));
}

Additionally, remember to account for the undefined value when subscribing to the function.

this.boxService.getDifferentFox(this.id.toString()).subscribe((res) => {
   this.result = '';
   if (res) {
      this.result = JSON.stringify(res);
   } else {
      alert('No record found');
   }
});

Take a look at the Demo

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

Display streaming data continuously within an HTML page using Angular 16

Currently, I am actively developing a stream API that receives data with a 'Content-Type' of 'text/event-stream'. Below is a snippet from my stream.service.ts: connectToSse(): Observable<any> { return new Observable((observer ...

Assess the equation twice using angular measurement

I am attempting to assess an expression that is originating from one component and being passed into another component. Here is the code snippet: Parent.component.ts parentData: any= { name: 'xyz', url: '/test?testid={{element["Te ...

Using ngFor to iterate over a list of items in Angular and displaying them conditionally using ng

In the process of creating a template, I am faced with this challenge: <ul> <li *ngFor='let link of links'> <ng-container *ngIf="link.type == 'complex'; then complexLink else simpleLink"></ng-container& ...

Error in Ruby Dynamic Array: `s` is not defined as a local variable or method in main Object (NameError)

Learning the ropes in ruby. I'm encountering an issue where my array isn't being recognized. After testing my code in irb, it seemed to function correctly, but when incorporating it into if statements, I encounter the error mentioned in the title ...

There is an issue with the hook call while trying to establish a context with a reducer

I am facing an issue while setting up the AppProvider component that utilizes a context and reducer to manage global data for my application. The problem seems to be arising from the useReducer hook used within the AppProvider. I have checked the error mes ...

Base URL for making Http Requests in an Angular application

I am currently working on an angular application that is hosted on a test server running IIS with a .net core backend. The application is set up on a virtual directory, for example www.myTestApp/crm (the actual domain name being fictional). During the buil ...

Using a secondary array to update values within a NumPy array

I have the following data set: [['CLU20'] ['CLZ20'] ['CLH21']] Furthermore, I possess an additional collection of data: ['CLU20' 'CLZ20' 'CLH21' 'CLM21' 'CLU21' 'CLZ21& ...

Generating React Components Dynamically using TypeScript

Attempting to generate an element in React using Typescript based on the given tagName passed as props, along with additional relative element properties depending on that particular tagName. Take a look at the code snippet below: type ElementProps<Tag ...

CreatePortalLink directs users to a payment URL instead of a dashboard

I am currently working on a project that utilizes the Stripe payments extension in conjunction with Firebase. The application is built using Next JS. After a user subscribes, I want to provide them with a tab where they can manage their subscription. The ...

What causes JavaScript parseFloat to add additional value in a for loop implementation?

I am facing a challenge where I need to convert an array of strings into an array of decimal numbers. The original array of strings is structured like this: var array = [" 169.70", " 161.84", " 162.16", " 176.06", " 169.72", " 170.77", " 172.74", " ...

Here's a revised version: "How to link a lambda layer with a function in a serverless.ts file using the

When working with the serverless framework using the typescript template, a serverless.ts file is generated. I am currently integrating lambda layers with existing functions and encountering a typescript error. The error message reads: "Type '{ Ref: ...

Angular problem: Cannot connect to 'formGroup' as it is not a recognized property of 'form'

Struggling to set up a simple form in Angular consisting of a label and an input field. Despite following suggestions to import FormsModule and ReactiveFormsModule, I'm still encountering errors as mentioned numerous times on StackOverflow. Here&apos ...

Delete an essential attribute from an entity

I am trying to remove a required property called hash from an object, but I keep encountering TypeScript or ESLint errors. All the properties of the interface are mandatory, and I do not want to make all properties optional using Partial. Here is the inte ...

The bidirectional binding feature of Angular2's ngModel seems to be malfunctioning

When trying to bind a model within an ngFor loop to an input field using ngModel, I encountered an issue where the value of the model would be visible in the model but not in the view when adding another item to the list. <div *ngFor="let model of ...

Tips for RETRIEVING a particular cookie value in Angular version 14

"I've integrated the ngx-cookie-service library in my Angular project, but I'm experiencing an issue where two different cookies are being retrieved upon login even though the session id is already set in the backend. How can I ensure that m ...

Discovering the power of Angular: Leveraging nativeElement to enhance your click handlers

Perhaps just a "stylish" yet effective solution... Here's what I have that is functional: // Template <div *ngFor="let media of period.media"> . . . <button #btn (click)="onDeleteClick(btn)" [attr.media-id]="media.ID"> ...

The Fusion of Apollo GraphQL Server and TypeScript: A Match Made

Lately, I've been immersed in a project that utilizes the node.js + express + typescript + Apollo server stack. During my research on Apollo client, I came across the TypeScript section, but surprisingly found little information regarding TypeScript f ...

Iterating through an array with conditional statements

I am currently considering the best approach to loop through an array in my code before proceeding further. I have some concerns about the link (var link = ... ) and the if statement. Is this the most optimal way to iterate over array1 and compare the val ...

Tips for maintaining type information when using generics in constructors

class Registry<Inst, Ctor extends new (...args: unknown[]) => Inst, T extends Readonly<Record<string, Ctor>>> { constructor(public records: T) { } getCtor<K extends keyof T>(key: K) { return this.records[key] } getIns ...

Create a .d.ts file for a custom JavaScript file

I am working on an application written in JavaScript and considering incorporating TypeScript for a new feature. Currently, I have a base class defined in JavaScript as shown below: // base.js module.exports = function BaseClass () { // ... ... }; M ...