Problem with Angular2 TypeScript Observables

Currently, I'm working with Angular 2.0.0-beta.0 and TypeScript 1.7.5

I have a scenario where I need to extract the resource identified by resourceId from the array of resources stored in this.resources, which is of type Observable<Resource[]>. Once extracted, this resource should be assigned to this.resourceToSave, which is of type Resource. This will enable me to update the changed resource in the database using the following code:

this.resourceService.updateResource(this.resourceToSave).subscribe()

I would appreciate assistance with writing the correct code for this operation.

import {bootstrap}         from 'angular2/platform/browser';
import {Component}         from 'angular2/core';
import {HTTP_PROVIDERS}    from 'angular2/http';
import {Observable}        from 'rxjs/Observable';
import {Subject}           from 'rxjs/Subject';
import 'rxjs/Rx';

import {Resource} from './classes/resource';
import {ResourceService} from "./services/resource-service";

@Component({
    selector: 'my-app',
    template: `
    <div class="container">
        <div>
            <h3>Resources Maintenance</h3>
            <div class="form-group">
                <label for="inputUser">Search</label>
                <input #inputUser (keyup)="search(inputUser.value)" autofocus>
            </div>
            <table style="width:65%" class="table-striped">
            <thead>
            <tr>
                <th>Resource</th>
                <th>Stock</th>
            </tr>
            </thead>
            <tbody>
            <tr *ngFor="#resource of resources | async">
                <td>{{resource.name}}</td>
                <td>
                    <div class="form-group">
                        <input type="number" class="form-control" [(ngModel)]="resource.stock" (change)="saveResource(resource._id)">
                    </div>
                </td>
            </tr>
            </tbody>
            </table>
        </div>
    </div>
    `,
    providers: [HTTP_PROVIDERS, ResourceService]
})

export class Test {

    private searchTermStream = new Subject<string>();

    private resources: Observable<Resource[]> = this.searchTermStream
        .debounceTime(500)
        .distinctUntilChanged()
        .switchMap((value: string) =>
            value.length > 0 ? this.resourceService.searchResources(value) : Observable.of([]))

    private resourceToSave: Resource;

    constructor(private resourceService: ResourceService) {}

    search(value: string) {
        this.searchTermStream.next(value);
    }

    saveResource(resourceId) {
        // Code implementation needed to handle 'this.resources' and 'resourceId' to assign value to 'this.resourceToSave'
        this.resourceService.updateResource(this.resourceToSave)
           .subscribe();
    }
}

bootstrap(Test);

Answer №1

Is it not possible to directly pass the resource when invoking the saveResource method within the context of the ngFor loop?

<tr *ngFor="#resource of resources | async">
  <td>{{resource.name}}</td>
  <td>
    <div class="form-group">
      <input type="text" class="form-control" [(ngModel)]="resource.stock" (change)="saveResource(resource)">
    </div>
  </td>
</tr>

This approach eliminates the need to retrieve the resource based on its id...

saveResource (resourceToSave) {
  this.resourceService.updateResource(resourceToSave)
       .subscribe();
}

Otherwise, it may become challenging to extract the list of resources from the observable. You would then have to store it in a specific property of your component...

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

Tips for showcasing unique validation error messages

My form includes a text area for the user to input JSON Code. If the entered text is not valid JSON, an error message should be displayed but unfortunately, it's not working as expected. Below is my custom validator code: import { AbstractControl, V ...

Analyze the entered text against the available choices in the combo box

I am working on a combo box that allows users to enter text. My goal is to display a warning message when the user types something that does not match any of the options in the combo box selection. Below is the code for my combo box: <mat-form-field app ...

Utilizing Angular and ASP .Net Web Api in conjunction with Plesk hosting platform

I have successfully created a website using Angular and .NET Framework 5.0. I was able to publish the Angular portion on Plesk and it is working correctly, but I am facing challenges in publishing the .NET Framework app and connecting it with Angular. ...

Having trouble pushing to an array in Angular typescript? It seems to be returning as undefined

As a newcomer to Angular with a basic understanding of JavaScript, I am attempting to create a program that can solve Sudoku puzzles. In a 9x9 grid, there are a total of 81 points or squares. To efficiently check for violations of Sudoku rules - no repeati ...

Ionic project initialization encounters a setback due to a dependency problem

After setting up Ionic by running npm install -g @ionic/cli I encountered an issue while trying to initialize a new project with the command ionic start ionic-test-app The initialization process failed due to an npm dependency error that mentioned a prob ...

Guide to utilizing the pdfjs worker in a React and TypeScript environment

I'm currently integrating pdfjs into a React and TypeScript project. import React from "react"; import * as pdfjs from "pdfjs-dist" export default function EditPdf() { React.useEffect(()=>{ const doc = pdfjs.getDocume ...

Hover Effect for 3D Images

I recently came across an interesting 3D Hover Image Effect that I wanted to implement - https://codepen.io/kw7oe/pen/mPeepv. After going through various tutorials and guides, I decided to try styling a component with Materials UI and apply CSS in a differ ...

The template reference variable has not been defined

The issue I'm facing is related to the template reference variable #newSkill on an input field. When passed as a parameter in the addToSkill() method, it works perfectly fine. However, when used in the chooseSkill() method triggered by clicking list ...

Having trouble integrating Firebase into the program

Why am I having trouble adding Firebase to my project? Could it be due to a mismatch between the local version of Angular and the global one? ...

Is it possible to add a value to a different entity in TypeORM?

I currently have the code below in my project; @Entity() export class User { @PrimaryGeneratedColumn() id!: number @Column() name: string } If I were to add a new User like this: {name: "Kahvi", gold: "200", exp: "500"} How can I implement a ...

Loop through a collection of elements of a certain kind and selectively transfer only certain items to a different collection of a different kind

When working with typescript, I am faced with the challenge of dealing with two arrays: interface IFirst{ name: string; age: number } interface ISecond { nickName: string; lastName: string; } myFirstArray: IFirst[]; mySecondArray: ISe ...

Moving between two separate Ionic applications within one combined Ionic + Angular project

I have two separate Ionic apps and a shared Angular library within one project. The first app is a website (app 1) and the second app is a dashboard (app 2), each with their own unique UI. I am looking to navigate between these two apps in a way that when ...

Selecting a filter for an array of objects

I'm struggling to implement a search feature in my mat-select DropDown. The existing options I've found online aren't quite working for me due to the object array I am passing to the Dropdown. Any assistance or guidance on this matter would ...

Testing an event within a subscription in Angular 4: A step-by-step guide

I am facing an issue with my component where I subscribe to an event in the constructor. To send an event, I use an event service: import {Injectable} from '@angular/core'; import {Observable} from "rxjs/Observable"; import {Subject} from "rxjs ...

How can I pass a variable from a parent component to a child component in Angular?

If we have a component where the user can embed their own content and access a variable exposed by the parent, how can we achieve this in Angular? Consider the following template of a parent component: @Component({ selector: 'parent', ...

TypeScript definition for a dispatcher within a map

I am in the process of creating a typed function that will utilize an object based on its key: const commandOrQuery = { CREATE_USER_WITH_PASSWORD: CreateUserCommandHandler, GET_USERS: GetUsersQueryHandler, }; The structure of commandOrQuery is as foll ...

Can an Angular 5 web application be developed without using Node.js/npm?

I want to develop an Angular 5 web application using Java, but my boss prefers not to use Node.js/npm. Is it possible to build an app without Node.js/npm and rely solely on Java? Most of the resources I've come across recommend using Node.js/npm, inc ...

Type of Data for Material UI's Selection Component

In my code, I am utilizing Material UI's Select component, which functions as a drop-down menu. Here is an example of how I am using it: const [criteria, setCriteria] = useState(''); ... let ShowUsers = () => { console.log('Wor ...

Is it possible to utilize a FOR loop in TypeScript to store an array in a variable?

Hey there pals! I could really use your brain power for a solution that requires some context. Our array ress is limited to items that meet a certain condition. After filtering the array, I need to store the new results in a different variable. I' ...

What methods can be used to resolve errors stemming from nesting classes within classes in TypeScript?

My experience with TypeScript is limited, and I'm facing an issue. The code appears as follows: 1) Main.ts: import gpbApi from '@/utils/api/gpbApi'; @Component export default class ExtendedDetailAccountComponent extends mixins(CurrentUserM ...