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

The function Event.target.value is coming back as null

I've been working on creating a timer window, and I've set up a separate component for it. However, I'm facing an issue with passing the time from the main component to the child component. The problem lies in the fact that the state of the ...

Capture individual frames from angular video footage

Trying to extract frames from a video using Angular has been quite challenging for me. While browsing through Stack Overflow, I came across this helpful post here. I attempted to implement the first solution suggested in the post, but unfortunately, I was ...

Testing Restful API Endpoints and Code Coverage with Node.js using Mocha

My time in Istanbul has been delightful, and I've been dabbling in different Node.js coverage libraries. However, I'm facing a challenge. Most of my unit tests involve making HTTP calls to my API, like this: it('should update the custom ...

Printing an Iframe using Safari print with Javascript results in an empty output

After researching the issue of printing blanks in Safari, I discovered that a white flash occurs before the print dialog can grab the content of the iframe. All my javascript works perfectly in every browser except for Safari. When attempting to print, it ...

Incorporating local JSON data into HTML: A Step-by-Step

I'm completely new to javascript and the utilization of json. What I want to accomplish is quite straightforward, although I am encountering difficulties. My objective is to create a website consisting of two pages: one that showcases artists and ano ...

Issue with converting string to Date object using Safari browser

I need to generate a JavaScript date object from a specific string format. String format: yyyy,mm,dd Here is my code snippet: var oDate = new Date('2013,10,07'); console.log(oDate); While Chrome, IE, and FF display the correct date, Safari s ...

Exploring ways to connect my React application with a node backend on the local network?

On my MacBook, I developed a react app that I access at http://localhost:3000. In addition, I have a nodejs express mysql server running on http://localhost:5000. The issue arises when I try to open the IP address with port 3000 in the browser of my Window ...

Tips for effectively utilizing the Angular ngIf directive for toggling the visibility of elements

<div *ngFor = "let element of myElements, let i=index" [ngClass]="{'selected':element[i] == i}"> <li> Name: {{element.element.name}}</li> <li> Description: {{element.element.description}}</li ...

Troubleshooting: CSS Styles not loading when passed as property in MUI withStyles

I am currently working on a react component that has a specific style defined as shown below: const StyledInnerItem = withStyles((theme) => ({ bgColor: { backgroundColor: (props) => { console.log('styledInnerItem color: ', props ...

What could be the reason for the failure of my class isInstance() check

Do you see any issues with the object being an instance of ChatRoom? Let me know your thoughts. Class: export class ChatRoom { public id?: number; public name_of_chat_room: string; public chat_creator_user_id: number; public chat_room_is_active: 0 ...

Sending an event from a child component to another using parent component in Angular

My form consists of two parts: a fixed part with the Save Button and a modular part on top without a submit button. I have my own save button for performing multiple tasks before submitting the form, including emitting an Event to inform another component ...

:Incorporating active hyperlinks through javascript

Hey there, I've encountered a little conundrum. I have a header.php file that contains all the header information - navigation and logo. It's super convenient because I can include this file on all my pages where needed, making editing a breeze. ...

A valid path is required in the form of a string when working with the HTTP module in Node.js

Currently, I'm working on an update checker that doesn't involve downloading the update. My main goal is to compare the version in the package.json file on GitHub with the one in my Electron app. However, when using this code, I encountered a "p ...

Is it possible in Angular.js to limit the visibility of a service to only one module or to a specific group of modules?

When working with Angular.js, the services declared on a module are typically accessible to all other modules. However, is there a way to restrict the visibility of a service to only one specific module or a selected group of modules? I have some service ...

The parameter type 'Object' cannot be assigned to the parameter type 'JSON' in the HttpClient GET method

Hey there! Currently, I'm deep into developing an Angular 6 + Flask application and I've encountered a bit of a snag: Error TS2345: Argument of type 'Object' is not assignable to parameter of type 'JSON'. This issue arises w ...

Struggling to grasp the concept of PHP LZW decompression function within JSend framework

I am currently working on converting the LZW decompressor from PHP to JavaScript and I have encountered a function that is giving me some trouble. function decompressLZW(aCodes) { var sData = ''; var oDictionary = []; for (var i = 0; i &l ...

What is preventing me from loading Google Maps within my Angular 2 component?

Below is the TypeScript code for my component: import {Component, OnInit, Output, EventEmitter} from '@angular/core'; declare var google: any; @Component({ selector: 'app-root', templateUrl: './app.component.html', st ...

Incorporating interactive elements within an NgFor loop

My goal is to develop a component that takes another component as a parameter and generates a collection of instances of this component, with the ultimate objective being the creation of a versatile backoffice. Here's an example of how it could look: ...

JavaScript not redirecting to HTML page as expected

I have developed a basic login page that makes an Ajax request to the backend. However, I am experiencing difficulties with redirecting the page upon successful login. The redirect function only seems to work 1 in 15 times, and I'm unsure of the reaso ...

Executing multiple requests simultaneously with varying identifiers following a waiting period

I am looking to send a GET request using the user_id key retrieved from the userData object. This is how the request should be structured: Let's assume we have userData defined as follows: var userData = [ { id: 1, user_id: ...