I possess an item, but unfortunately, I am only able to save the first object from this possession

I have an object, but I can only save the first item from this object.

Interface:

export interface PhotoToCreate {
 
     albumName: string;
   albumTitle: string;
   ImageNameO : string;
 imageNameT : string;
  
}

Component

import { Component, OnInit, Injectable } from '@angular/core';
import { PhotoToCreate } from '../_Classes/photo-to-create.model';
import { PhotoModule } from '../_Classes/photo-module.model';
import { HttpClient } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
@Component({
  selector: 'app-alerts',
  templateUrl: './alerts.component.html',
  styleUrls: ['./alerts.component.scss']
})
export class AlertsComponent implements OnInit {

  public isCreate: boolean;
  public albumName: string;
  public albumTitle: string;

  public photo: PhotoToCreate;
  public photos: PhotoModule[] = [];
    public response:{dbpathsasstring: ''}

  constructor(private http: HttpClient) { }

  ngOnInit() {   
   this.isCreate = true;
  }
  

  public spliturl = (serverss: string)=> {
   if (serverss.includes(",")) {
    for(let i = 0; serverss.length; i++) {
      console.log(i)
      var serpatharr=serverss.split(',');
      serverss=serpatharr[i];
    }
    return serverss;
  }
} 
  
  public onCreate = () => {
    this.photo  = {
      albumName: this.albumName,
      albumTitle: this.albumTitle,
      ImageNameO : this.spliturl(this.response.dbpathsasstring),
      imageNameT : this.spliturl(this.response.dbpathsasstring)
    } 

    this.http.post('https://localhost:44318/api/PhotosAlbums', this.photo)
    .subscribe(res => {
       this.getUsers();
       this.isCreate = false;
    });
  }

  private getUsers = () => {
    this.http.get('https://localhost:44318/api/PhotosAlbums')
    .subscribe(res => {
      this.photos = res as PhotoModule[];
    });
  }

  public returnToCreate = () => {
    this.isCreate = true;
  }

  public uploadFinished = (event) => {
    this.response = event;
  }

  public createImgPath = (serverPath: string) => {
    if(serverPath.includes(",")) {
      var serverPathArr = serverPath.split(',');
      serverPath = serverPathArr[0];
    }
    return `https://localhost:44318/${serverPath}`;
  }
}

 
html template
<article class="container container-fluid">
  <section class="create" *ngIf="isCreate">
    <h1>Create User</h1>
    <form>
      <div class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control" id="albumName" name="albumName" placeholder="Enter your name" [(ngModel)]="albumName">
      </div>
      <div class="form-group">
        <label for="address">Address</label>
        <input type="text" class="form-control" id="albumTitle" name="albumTitle" placeholder="Enter your address" [(ngModel)]="albumTitle">
      </div>
      <app-upload (onUploadFinished)="uploadFinished($event)"></app-upload>
      <div class="row">
        <div class="offset-md-5 col-md-2">
          <button type="button" class="btn btn-primary" (click)="onCreate()">Create </button>
        </div>
      </div>
    </form>
  </section>

  <section class="users" *ngIf="!isCreate">
    <table class="table table-striped">
      <thead>
        <tr>
          <th scope="col">Image</th>
          <th scope="col">Name</th>
          <th scope="col">Address</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let photo of photos">
          <td><img [src]="createImgPath(photo.ImageNameO)" alt="profile picture" style="width:60px; height:60px;"></td>
          <td>{{photo.albumName}}</td>
          <td>{{photo.albumTitle}}</td>
        </tr>
      </tbody>
    </table>
    <div class="row">
      <div class="offset-md-10 col-md-2">
        <button type="button" class="btn btn-primary" (click)="returnToCreate()">New User</button>
      </div>
    </div>
  </section>
</article>

Returned path from API: Resources\Images\c7ef86f6-a032-4124-9327-142f0b1e99371.png,Resources\Images\4801b60c-7d82-4e51-aab2-db2da0f9647c2.png

This function saves the first image

public spliturl = (serverss: string)=> {
  if (serverss.includes(",")) {
    
    var serpatharr=serverss.split(',');
    serverss=serpatharr[0];
  }
  return serverss;
}
  
  

The path is stored in both fields Resources\Images\c7ef86f6-a032-4124-9327-142f0b1e99371.png,Resources\Images\4801b60c-7d82-4e51-aab2-db2da0f9647c2.png

However, using this method to split the path

only the first image is saved in ImageNameO = Resources\Images\c7ef86f6-a032-4124-9327-142f0b1e99371.png

The second field cannot save the path, imageNameT = Resources\Images\4801b60c-7d82-4e51-aab2-db2da0f9647c2.png saved as null

How can I save the images with correct paths?

Say:

ImageNameO = Resources\Images\c7ef86f6-a032-4124-9327-142f0b1e99371.png

ImageNameT = Resources\Images\4801b60c-7d82-4e51-aab2-db2da0f9647c2.png

Answer №1

The first step is to verify the functionality of the spliturl function.

Once you have confirmed that the spliturl is functioning correctly, proceed with the following steps:

If the spliturl function is returning a string, then it should be working properly.

However:

If the spliturl function is returning an Array of Strings,

you need to modify your PhotoToCreate interface as follows:

export interface PhotoToCreate {
  albumName: string;
  albumTitle: string;
  ImageNameO: Array<string>;
  imageNameT: Array<string>;
}

[UPDATE]

Based on feedback, it seems that your query needs more clarity.

Therefore, the concept revolves around the presence of the onCreate function

onCreate = () => {
  this.photo  = {
  albumName: this.albumName,
  albumTitle: this.albumTitle,
  ImageNameO: this.spliturl(this.response.dbpathsasstring),  
  imageNameT: this.spliturl(this.response.dbpathsasstring)
}

The value of this.response.dbpathsasstring is:

this.response.dbpathsasstring = 'Resources\Images\c7ef86f6-a032-4124-9327-142f0b1e99371.png,Resources\Images\4801b60c-7d82-4e51-aab2-db2da0f9647c2.png'

You now intend to:

  1. Set ImageNameO to

    'Resources\Images\c7ef86f6-a032-4124-9327-142f0b1e99371.png'

  2. Set imageNameT to

    'Resources\Images\4801b60c-7d82-4e51-aab2-db2da0f9647c2.png'

Your focus should now be on analyzing your spliturl function.

Your current spliturl function:

public spliturl = (serverss: string) => {
  if (serverss.includes(",")) {
    for(let i = 0; serverss.length; i++){
      console.log(i)
      var serpatharr=serverss.split(',');
      serverss=serpatharr[i];    
    }
    return serverss
  }
}

[Fixing] based on the explanation above

To address the issue highlighted in the explanation,

spliturl = (serverss, index) => {
  if (serverss.includes(",")) {
    const serpatharr = serverss.split(',');
    serverss = serpatharr[index];
    
    return serpatharr[index];
  }

  return serverss; // Remove this line if you dont want to return anything
}

Update your onCreate function accordingly:

onCreate = () => {
  this.photo  = {
  albumName: this.albumName,
  albumTitle: this.albumTitle,
  ImageNameO: this.spliturl(this.response.dbpathsasstring, 0),  
  imageNameT: this.spliturl(this.response.dbpathsasstring, 1)
}

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

How to Implement Double Click Functionality in VueJS

I am facing an issue with my table where the columns have varying widths. To implement sticky headers, I need to calculate the column widths accurately. Initially, I created a function that increases the column width when double-clicking on the header. Su ...

Hand over the component method as an argument to a class

One of my components, called First, is responsible for creating a new instance of a Worker class. During the creation process of this class, I intend to pass the Read method as a callback method. Once this class completes its task, it will then invoke thi ...

Angular ngx-translate not displaying image

My Angular application is utilizing ngx-translate to support multiple languages. I am trying to dynamically change an image based on the language selected by the user. However, I am facing difficulty in updating the image when a language is clicked. The ap ...

Convert the assignment of a.x=3 to the setter method a->setX(3) using the provided script

As I transition a portion of my code from JS to C++, I find the need to refactor direct instance variable assignments into setter methods: a.xx=3; to a->setXx(3); along with getter methods: ...a.xx... to ...a->getXx()... Currently, I am utilizing ...

Implementing real-time data updates on a webpage using Node.js

Currently, I am faced with the challenge of updating values on my page in real-time without the need for constant webpage refreshing. To illustrate, consider a scenario where a user filters a real estate website by location and receives results showing the ...

What sets apart the `ajax:send` event from the `click` event is that it specifically triggers an ajax

Currently, I am utilizing ajax requests with coffee in my Rails project as shown below. $('#reload').on( 'click': -> $('#response').html "<div class='panel'><img src='assets/load.gif'/> ...

Understanding ExpressJS: Exploring the distinctions between ?, +, * in string patterns and regular expressions

Hello there! As a newcomer to Express, I've been on the hunt for a thorough explanation of string patterns with no luck. The path-to-regexp documentation has left me scratching my head. In particular, I'm grappling with this somewhat enigmatic s ...

Issue with div element not stretching to 100% width

I am currently working on a fluid layout design where the template includes a header, menu, and body section. <div class="w100 h100"> <div id="headerBox" style="height: 10%;" class="w100"> <div style="width: 80%;" class="lfloat ...

What could be causing the jQuery effect to not function properly?

After completing a course on Codecademy, I successfully ran the code. However, I prefer to copy and paste the code into my own jquery folder for future reference and practice. The objective of this project was to make the element 'krypton' bounc ...

Is it possible for the HTML data attribute to store a direct link to a specific DOM element?

Can the HTML data- attributes be used to store a reference to another DOM element? As shown in this jQuery example: var domel1 = document.getElementById("#mydiv"); var domel2 = document.getElementById("#mydiv2"); $(domEl1).attr('data-domel', dom ...

Angular progress tracker with stages

I have been exploring ways to create a progress bar with steps in Angular 12 that advances based on the percentage of progress rather than just moving directly from one step to another. This is specifically for displaying membership levels and indicating h ...

Display PDF file retrieved from the server using javascript

I am currently working on a web application using JavaScript, jQuery, and Node.js. I need to receive a PDF file from the server and display it in a new browser window. While I believe I have successfully received the file on the client side (the window sh ...

The function to automatically refresh the page upon the user receiving a new message is currently malfunctioning

Having trouble with the page reloading when a new message is received by the user. I have been working on developing a PHP chat application that allows both admins and users to chat with each other. Whenever a new message is sent, the user has to manuall ...

Determining the quantity of displays

Can we detect the number of screens in use using JavaScript or jQuery? We are working on an application that should not be displayed on multiple screens, even if the hardware allows for it. Appreciate any assistance with this matter. Thank you. ...

Running into trouble importing an ES module in Node.js during a migration

Currently, I am in the process of developing a straightforward application for my personal project using ExpressJS. To manage database changes, I have opted to utilize sequelize ORM. My current objective is to rollback a migration, and to achieve this goal ...

Explore all user-defined properties of a specified type using the TypeScript Compiler API

Consider the following model structure: interface Address{ country: string; } interface Author{ authorId: number; authorName:string; address: Address; } interface Book{ bookId:string; title: string; author : Author; } I want to iterate th ...

The ValidationSchema Type in ObjectSchema Seems to Be Failing

yup 0.30.0 @types/yup 0.29.14 Struggling to create a reusable type definition for a Yup validationSchema with ObjectSchema resulting in an error. Attempting to follow an example from the Yup documentation provided at: https://github.com/jquense/yup#ensur ...

Store a JSON object without creating a reference to it

My issue is presented in a much simpler manner. Here is the json (you can view it here if you wish) {"resource":[{"id":"1408694994","obj":[{"id":"1","action":[{"name":"ON","id":"301"},{"name":"OFF","id":"302"}]},{"id":"2","action":[{"name":"ON","id":"303 ...

Transmit: Forwarding information back to the recipient

My goal is to send an Http Post request (Registration form) using Angular, have it processed in the API, and if any errors occur like Please enter a username..., I want to return an error message to the client. Below is the Angular code for reference. Than ...

What is preventing me from being able to effectively transmit the array using the POST method in Express?

As a newcomer trying to learn Express, I believe I am on the right path, but I am currently facing some challenges with the POST method. The issue I'm encountering is as follows: Whenever I send a POST request to an HTTP file, I receive an empty ob ...