Encountering a 404 (Not Found) error while trying to access a null resource in Angular at http://localhost

Currently, I am developing an angular application with ng9.

I have a specific div where I need to display an avatar using an image fetched from the API in my component.ts file:

....

export class HomeComponent implements OnInit {

  nextLaunch$: Observable<SpacexNext>;

  panelOpenState: true;

  search = '';

  constructor(
    private spacexService: SpacexService,
    private sanitizer: DomSanitizer
    ) { }

  ngOnInit(): void {
    this.nextLaunch$ = this.spacexService.getNextLaunch();
    }
    
...

In the .html file:

<div mat-card-avatar *ngIf="(nextLaunch$ | async)?.links?.patch?.small !== null" [style.backgroundImage]="'url('+(nextLaunch$ | async)?.links?.patch?.small+')'" class="example-header-image">
</div>

The avatar displays correctly without any issues, but I keep encountering an error in the browser console:

GET http://localhost:4200/null 404 (Not Found)

Do you have any suggestions on how to resolve this error?

Additional Information

The API functions as expected and returns data properly. The avatar image shows up without any trouble. My main concern is addressing the error message that pops up in the browser console. I did some research and found that the issue could be related to the async pipe, but I personally prefer it over the subscribe method.

Thanks in advance.

Answer №1

The async pipe may not be the best choice for this scenario.

It is recommended to create a separate variable in your component to store the result of your asynchronous task.

public smallPatchUrl: string;

(Assuming that the URL is of type string, make changes as needed).

Within your ngOnInit method, include:

this.spacexService.getNextLaunch().subscribe(x => {
  if (x && x.links && x.links.patch) {
    this.smallPatchUrl = x.links.patch.small;
  }
});

In your template file, use the following for your component:

*ngIf="this.smallPatchUrl" [style.backgroundImage]="'url(' + this.smallPatchUrl + ')'"

This approach ensures that your component will not attempt to access this.smallPatchUrl when it is null or undefined.

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

Utilizing flatMap to implement nested service calls with parameters

Recently, I encountered an issue while working on a service call to retrieve data from a JSON file containing multiple items. After fetching all the items, I needed to make another service call to retrieve the contents of each item. I tried using flatMap f ...

I'm stuck trying to figure out all the parameters for the MapsPage component in Angular 2

Currently, I am utilizing Angular2 with Ionic2 for my mobile app development. Everything was working flawlessly until I decided to incorporate a new module for Google Maps navigation. Specifically, I am using phonegap-launch-navigator for this purpose. The ...

Encountering "Invalid hook call" error with React Router while integrating Higher Order Components for authentication

Dealing with an error: React Router shows "Invalid hook call" with higher-order components for authentication Dilemma I have developed two distinct approaches for authentication wrappers in my React components with React Router. The first method functions ...

What is the best way to search and sort a MatTable with special characters like accents and diacrit

I need to implement a name filtering functionality for a table, regardless of whether the user includes accents or not. For instance: If the user types "hydrogen", the result should display "Hydrôgen" from the table. I am using Angular 8.1.3 and Angula ...

Generate a blueprint for a TypeScript interface

In my coding project, I've been noticing a pattern of redundancy when it comes to creating TypeScript interfaces as the code base expands. For example: interface IErrorResponse { code: number message: string } // Feature 1 type FEATURE_1_KEYS = ...

Running the Angular application using index-dev.html instead of index.html with angular-cli

I created an Angular project using angular-cli (version 1.0.2). However, I want to run it from index-dev.html instead of index.html. Both files will have the same content, just different names. When not using angular-cli, I know how to configure lite-serv ...

Encountering an issue with npm installation on AWS Ubuntu

I need assistance with deploying my Angular 2 application on AWS Ubuntu. While I was able to successfully install npm on Ubuntu, I encountered an error when trying to build my application using "npm install". The error mentions something about "extract:typ ...

What is the process for developing a custom pipe in Angular 12 with ngx-translate and internationalization support?

I've been working on internationalization for my angular project, which is an admin portal using @ngx-translate. Unfortunately, I've hit a roadblock and need to start over with the internationalization task. Any suggestions on how to approach thi ...

Failing unit test for ngrx effect with { dispatch: false } setting and action returned by the effect

Take a look at this code snippet: loadProducts$ = createEffect(() => this.actions$.pipe( ofType(requestLoadProducts), switchMap(action => this.service.load().pipe( map(data => loadProducts({products: data})) )) ) , { dispatch ...

Creating a PDF file with Angular 7: A step-by-step guide

I need to create a PDF report using data provided by the user and save it in an object. I've encountered methods that involve creating an HTML page, taking a screenshot, and then converting it to PDF. However, I'm seeking a solution to generate a ...

ReactJS Redux Provider fails to accept the store

I'm currently in the process of migrating my redux store from using "createStore" to "configureStore" due to the deprecation of "createStore". I am working with ReactJS 17 and TypeScript, with the following versions of Redux / Redux dependencies: &quo ...

Stop the direct importing of modules in Angular applications

I have a feature module that declares components and also configures routing through a static function. @NgModule({ declarations: FEATURE_COMPONENTS, entryComponents: FEATURE_COMPONENTS, imports: [ UIRouterModule, ... ] }) export class Fea ...

I'm looking to learn how to implement the delete method in an API using TypeScript. Can anyone help me out

I am seeking guidance on utilizing 'axios' within 'nuxt.js'. I have experimented with sample data, and I am particularly interested in learning how to utilize the 'axios' method within 'nuxt.js' using TypeScript. T ...

What is the syntax for creating ES6 arrow functions in TypeScript?

Without a doubt, TypeScript is the way to go for JavaScript projects. Its advantages are numerous, but one of the standout features is typed variables. Arrow functions, like the one below, are also fantastic: const arFunc = ({ n, m }) => console.log(`$ ...

Expanding User Type to Include Extra User Data Using NextAuth.js

I encountered a dilemma where I needed to include the "profile" property in my section object to cater to different user personas in my application. However, despite retrieving the logged-in user's data from the backend and storing it in the NextAuth. ...

A TypeScript function that returns the ReturnType of a specific callback function

Is it possible to define an annotation for a function that accepts a callback, and have the function return type determined by the callback's return type? // Suppose the callback takes a number as argument function processCallback(cb: (arg:number) =&g ...

"Discovering the secrets of incorporating a spinner into Angular2 and mastering the art of concealing spinners in Angular

When experiencing delay in image loading time, I need to display a spinner until the image loads completely. What is the best way to achieve this on the Angular 2 platform? <div id='panId' class="container-fluid" > This section ...

Is there a method to automatically select or deselect a checkbox based on the incoming value in Angular?

When new data comes in, the table gets populated and I can't specify that "A" should be checked while "D" shouldn't. re(ref: getrefactormodel, count:number){ let data= this.fb.group({ word_to_rename: [ref.word_to_rename, Vali ...

Utilizing Input Value from Parent Component in Angular TypeScript File: A Guide

Is there a way to manipulate the @Input()items in the child-component.ts file before passing it to child-component.html? Currently experiencing an issue where I get an empty object when logging in the ngOnInit method. child-component.ts @Input()items: ...

Creating a dynamic path to an imported file in React: A step-by-step guide

Struggling with a dilemma regarding dynamically generated paths for importing files in React. I have utilized the map() function to generate a dynamic part of the code, consisting of a repetitive sequence of div elements, each housing an audio element. The ...