What are the best practices for incorporating the "photo.service" feature effectively?

I'm currently working with Angular 4 and have encountered a 404 error when trying to display an image:

GET http://localhost:4200/photos/original/missing.png 404 (Not Found)

Error details:
- DefaultDomRenderer2.setProperty @ platform-browser.es5.js:2895
- AnimationRenderer.setProperty @ animations.es5.js:534
- DebugRenderer2.setProperty @ core.es5.js:13740
- setElementProperty @ core.es5.js:9401
(and more detailed steps...)

What could be causing this issue?

In my photo.service.ts file:

import {Injectable} from '@angular/core';
import {Photo} from '../../models/photo.model';
import {handleError} from "../../shared/functions";
import { AuthService } from '../auth/auth.service';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class PhotoService{
    constructor(
        private _authService:AuthService
    ){ 
    }

    getPhotos(){
        return this._authService.get('photos')
            .map(result => result.json())  
    }

}

Inside photo.component.ts:

import { Component, OnInit} from '@angular/core';
import { AuthService } from "../../../services/auth/auth.service";
import { PhotoService} from "../../../services/photo/photo.service";
import { Photo} from "../../../models/photo.model";

@Component({
  selector: 'photo',
  templateUrl: './photo.component.html',
  styleUrls: ['./photo.component.scss'],
  providers: [PhotoService]
})

export class PhotoComponent implements OnInit {

  photos: Array<Photo>;

  filteredPhotos =[];

  constructor(
    protected authService:AuthService,
    private servPhoto: PhotoService
    ) {}

  ngOnInit() {
    this.loadPhotos();
  }

  private loadPhotos() {
    let filteredPhotos;
    if (this.servPhoto) {
      this.servPhoto.getPhotos().subscribe(
        photo => {
          if(!this.authService.currentUserData) {    
            return; 
          }
          this.photos = photo;
          this.filteredPhotos = this.photos.filter(
            (photo) => photo.users_id ==  this.authService.currentUserData.id
          );
        }
      );
    }
  }

}

Within the photo.model.ts file:

export class Photo{
    constructor(
        public users_id: number,
        public photo: Blob
    ) { }
}

For the photo.component.html file:

<div class="container-fluid" *ngIf="authService.currentUserData">
   <img class="img" *ngFor="let photo of filteredPhotos" src="{{ photo.photo }}">
</div>

Lastly, here is the JSON data being used:

[{"users_id":36,"photo":"/photos/original/missing.png"},
{"users_id":1,"photo":"/photos/original/missing.png"},
{"users_id":1428,"photo":"/photos/original/missing.png"}]

Answer №1

The src="{{ photo.photo }} in your code is referencing an image path that doesn't exist based on the JSON data

"photo":"/photos/original/missing.png"
.

The error message you're seeing:

GET http://localhost:4200/photos/original/missing.png 404 (Not Found)
is indicating that the image cannot be found.

What mistake did I make?

There's no specific mistake in your code. It's simply trying to fetch an image at a location where there isn't one present. To resolve the 404 error, ensure that an image exists at the URL mentioned in the JSON data.

Answer №2

It appears that the service you are using is providing JSON data, but your class is specifically looking for a Blob data type.

Answer №3

Here's a different approach:

Consider trying this method:

<div *ngIf="authService.currentUserData">
<div class="container-fluid" *ngFor="let photo of filteredPhotos" >
   <img class="img"  [src]="photo.photo">
</div>
</div>

Answer №4

To find the specified folder, you must navigate to a folder within either the angular.json or angular-cli.json file.

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "frontend"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico",
        "photos"   //<==== make sure to add this folder source here     
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.css",
        "../node_modules/font-awesome/css/font-awesome.min.css",
        "../node_modules/perfect-scrollbar/css/perfect-scrollbar.css",
        "./assets/sass/material-style.scss",
        "./assets/css/style.css",
        "../node_modules/primeicons/primeicons.css",
        "../node_modules/primeng/resources/themes/omega/theme.css",
        "../node_modules/primeng/resources/primeng.min.css",
        "../node_modules/quill/dist/quill.core.css",
        "../node_modules/quill/dist/quill.snow.css"
      ],
      "scripts": [
        "../node_modules/jquery/dist/jquery.js",
        "../node_modules/quill/dist/quill.js",
        "../node_modules/bootstrap/dist/js/bootstrap.js",
        "../node_modules/bootstrap-material-design/dist/js/ripples.min.js",
        "../node_modules/bootstrap-material-design/dist/js/material.min.js",
        "../node_modules/arrive/src/arrive.js",
        "../node_modules/chart.js/dist/Chart.js",
        "../node_modules/moment/moment.js",
        "../node_modules/perfect-scrollbar/dist/perfect-scrollbar.min.js",
        "../node_modules/bootstrap-notify/bootstrap-notify.js",
        "../node_modules/hammerjs/hammer.min.js"
      ],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "src/tsconfig.spec.json",
      "exclude": "**/node_modules/**"
    },
    {
      "project": "e2e/tsconfig.e2e.json",
      "exclude": "**/node_modules/**"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {
    }
  },
  "warnings": {
    "typescriptMismatch": false
  }
}

After that, halt your ng or npm and restart it.

Now use ng serve or npm start. This should resolve the issue.

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

A step-by-step guide on integrating image uploading from a URL to Amazon S3 using Angular5

I am looking for a way to directly upload images from a URL to my Amazon S3 bucket. Currently, when I use the provided code, the result is the url itself instead of the actual image... Within my Angular5 controller : import { AwsService } from '../ ...

Updating Cart Array in Angular 4 when Adding a New Item

I'm currently using angular 4 and I have encountered an issue in the code where adding a new product to the cart overwrites the existing item instead of appending it to the array. Here is a screenshot illustrating the problem cart.service.ts export ...

Updating the svgIcon attribute in the mat-icon component in Angular version 5

Is it possible to change the icon of a mat-button-toggle when the button is pressed by modifying the svgIcon property? Thank you for your help. <mat-button-toggle value="left"> <mat-icon class="mat-icon" svgIcon="Thermometer" role="img" ari ...

What is the reason buttons in mat-menus do not submit?

I have implemented a mat-menu to showcase a list of choices for the user. The objective is to trigger the submission of my formGroup when a user selects an option from the menu. dropdown.component.html <form [formGroup]="myForm" (ngSubmit)=onSubmit(my ...

Angular 8 encountered a 404 (Not Found) error when trying to POST to http://localhost:4200/assets/data/students.json

I'm currently working on a project that involves fetching array data through HTTP and should also allow for the addition of new arrays using HTTP. However, every time I attempt to post a new array, I encounter the following error: POST http://local ...

Retrieving information from a child modal window in an Angular parent component

In the scenario where there is data in two tables on the left and right sides, a modal popup window will open when a user clicks a link from the parent component. Upon selecting a radio button from the window, it should correspond to the selected link in t ...

What are the two different ways to declare a property?

I am trying to update my interface as shown below interface Student{ Name: String; age: Number; } However, instead of the current structure, I would like it to be like this interface Student{ Name: String; age | DOB: Number | Date; } This means t ...

I am looking for a way to automatically close an existing window and open a new window whenever a button is clicked in Angular. How can I achieve this

Looking to use window.open() to open a new window, but need to ensure that if the same window is already open from before, it must be closed before opening a new one. ...

Passing values from Angular 2 selector to HTML template using data binding

Is there a way to easily transfer basic values from my selector, like class and id, to the template? I have successfully imported my component into a module and included the imported selector in the HTML of the importing component. What I aim to achieve is ...

Automatically insert a hyphen (-) between each set of 10 digits in a phone number as it is being typed into the text

I'm attempting to automatically insert a hyphen (-) in between 10 digits of a phone number as it is being typed into the text field, following North American standard formatting. I want the output to look like this: 647-364-3975 I am using the keyup ...

Angular 10 error: Inconsistencies found in translation strings IDs

Our application is running Angular 10.1.4 and we are using the command ng xi18n --ivy --format=xlf --output-path apps/my-app/src/i18n to extract strings. After converting xlf to json format, we load the json translations during app initialization with load ...

Unable to successfully process HTTP Request Unsubscribe commands

When working with my component, I am retrieving data from a JSON file through services and subscribing to it. There is a condition check in place to stop the subscription once a specific criteria is met, but unfortunately, it doesn't seem to be workin ...

Combine various HTTP requests in Angular using RxJS, ensuring that the outer request is emitted immediately

I'm struggling to fully understand some aspects of RxJS operators. Below is some code snippet from a component: extendedOrders$ = this.salesService.getOrders().pipe( switchMap(orders => { return forkJoin(orders.map(order => { return ...

Tips for creating basic Jasmine and Karma tests for an Angular application to add an object to an array of objects

I have developed a basic Angular project for managing employee data and I'm looking to test the addProduct function. Can someone guide me on how to write a test case for this scenario? I am not using a service, just a simple push operation. Any assist ...

In an Angular component, attempt to retrieve the data type of a class property

Discover how to retrieve the type of properties from an object by following this Typescript tutorial link. However, it seems to be behaving like Javascript and returning the value of the property instead of the type: const x = { foo: 10, bar: 'hello! ...

flushMicrotasks does not function properly in conjunction with the image.onload event

Working on an Angular project, I'm currently developing an object with an image field. The method responsible for loading the image returns a promise that resolves in the onload function of the image. When trying to test this method using the flushMi ...

Develop a new data structure using the parameter type as a foundation

I am grappling with a generic function that returns another function. While typing it, there might be required keys. These required keys are optional for the initial function, but become mandatory for the subsequent function if they were not provided init ...

Using a unique component within PipeTransform in Angular 2: A guide

I am facing an issue where my custom component Status is not displaying correctly within my pipe transform. The browser only shows the value, without the < Status /> tags. It seems like the component is not being called at all. Can someone please ex ...

Using TypeScript without specifying a specific argument in the any type

My function accesses local/session storage, but there is a condition that it can only be called if the window is defined. This function takes a generic args argument which I simplified to have a type of any[]. While using the useSessionStorage function, ...

Error in Node: JSON parse failure due to invalid token "'<'" and ""<!DOCTYPE ""

Every time I attempt to run node commands or create a new Angular project, I encounter the following error. Node version 20.11.0 NPM version 10.2.4 https://i.sstatic.net/Dg6BU.png https://i.sstatic.net/ZwN1Q.png ...