Retrieve JSON data from a 404 response using the Http.get() method

I am attempting to retrieve JSON from a 404 response, but I am only receiving the

Response {_body: "{myJSON}", status: 404, ok: false, statusText: "Not Found", headers: Headers…}

How can I access the object itself so that I can display it in my HTML using something like {{error.text}}, similar to how I did with http.get()?

Below is my code :

getList(): Promise<Response> {
    return this.http.get(this.apiUrl+'list/')
.toPromise() 
.then(response => { 
  console.log(response.json()); return response.json()})
.catch(this.handleErrorPromise)   
}
//if an error ocurred while doing api calls 
  private handleErrorPromise (error: Response | any) {
  console.error("EEEEE" + error.message || error);
  return Promise.reject(error.message || error);
    }

When it reaches the .then part, everything works fine and it returns an object which I can use in my component (I'm currently implementing it this way... please let me know if there's a better approach)

ngOnInit(): void {
this.ListServiceProvider.getList().then( 
list=> {this.mList= list; console.log(list)}, 
error => {this.errorMessage = error; console.log(error)}); 
}

In my HTML, I have a *ngIf=errorMessage set up to show when there is an error, however, it doesn't display the JSON as expected. Can you help me identify what may be wrong with my code?

Answer â„–1

Try utilizing the new Angular If/else feature for this scenario

  <ng-template #fetching>
    //You can also add an optional ngIf check here
    <p *ngIf = "errorMessage">{{errorMessage?.imageURL}</p> // Update made after receiving feedback
  </ng-template>

  <p *ngIf="mList; else fetching;">
  //Perform actions when data is available, otherwise default to the else template
  </p>

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

Exploring how to traverse a <router-outlet> within its container

I am attempting to switch the active component within a from its parent. After observing how Ionic achieves this, I believe it should resemble the following (simplified): @Component({ template: '<router-outlet></router-outlet>' } ...

Updating data in Angular reactive forms using asynchronous dropdowns

I am currently developing an Angular application and have encountered an issue that I am unable to resolve by solely reading the documentation. One of the components in my application is responsible for displaying a form: https://i.stack.imgur.com/p5KEU. ...

Encountering an Angular 12 error 401 upon refreshing the page

Currently, I am working on a login form using angular 12 with Spring Boot that includes basic authentication spring security. When a user successfully logs in, they are directed to the main page which offers CRUD actions as depicted in the images linked be ...

What is the best way to transform typescript defined string types into an array of strings?

I'm attempting to extract all defined types from a variable in a constructor. export interface TestType { resultType?: 'NUMBER' | 'STRING' | 'DATE' | 'ENUM' | 'AMOUNT' ; } My expectation is to achie ...

Can a discriminated union be generated using mapped types in TypeScript?

Imagine you have an interface called X: type X = { red: number, blue: string } Can a union type Y be created using mapped types? If not, are there other ways to construct it at the type level? type Y = { kind: "red" payload: number } | ...

Creating a personalized tooltip in Angular for a bubble chart with ApexCharts

I'm currently working on customizing the tooltip for a bubble chart using the ApexCharts library. Here is the link to my project. ...

Encountering an Error in Angular with Jest: TypeError Unable to Access Property 'ngModule' from null

Challenge I have been trying to implement Jest testing for my Angular application. Following the guidelines provided by jest-preset-angular, I encountered an error when running tests with Bazel using this target: FAIL services/client/src/app/app.componen ...

Unable to utilize 'inject' in the beforeEach function for unit testing in AngularJS (FUSE Admin) with Karma

I recently utilized the FUSE Admin app in my project and found it to be quite helpful. You can check it out here: . Although I have successfully run this code on another project without any issues, I encountered a problem with injecting the service and co ...

Exclude promises from a type in TypeScript

Here is my TypeScript snippet: async function get_string(){ return "hello" } var the_string = get_string() In the code, the type of the_string is Promise<string> I am interested in removing the Promise from the type of the_string and m ...

Structural directive fails to trigger event emission to parent component

Following up on the question posed here: Emit event from Directive to Parent element: Angular2 It appears that when a structural directive emits an event, the parent component does not receive it. @Directive({ selector: '[appWidget]' }) export ...

Dynamically importing TypeScript interfaces for React code splitting

Is it possible to utilize dynamic import('path') for an exported interface? ...

Enable Ace Editor's read-only mode

I'm having some difficulty getting my ace-editor to work in read-only mode. I'm working with Angular 9 and I've attempted the following approach: In my HTML file, I have the following code: <ace-editor mode="java" theme="m ...

Trouble with 'import type' declaration causing build issues in a Next.js project

Having trouble importing the Metadata type from the next module. The code snippet below is directly from the Next.js documentation. THE ISSUE client.js:1 ./app/layout.tsx:3:12 Syntax error: Unexpected token, expected "from" 1 | import React from 'r ...

Is it acceptable to use JavaScript files in the pages directory in NEXTJS13, or is it strongly advised to only use TypeScript files in the most recent version?

In the previous iterations of nextJS, there were JavaScript files in the app directory; however, in the most recent version, TypeScript files have taken their place. Is it still possible to begin development using JavaScript? I am working on creating an a ...

What causes the variable assigned in the outer subscription's scope to change as the inner subscriptions change?

In my Angular 6 code snippet provided below, I am facing an issue: ngOnInit() { this.route.queryParams.subscribe((params: Params) => { const stuffId: string = params.stuffId; this.service.getState().subscribe((state) => { ...

Issues arise with PrimeNG multiselect onItemClick functionality following an update to version 7

I am currently working with a MultiSelectComponent that extends the primeng MultiSelect functionality. Recently, I updated from version 6.1.6 to 7.0.4. <ul class="not-important" <li *ngFor="let option of options; let i = index" class="not-import ...

What is the best way to generate an object in TypeScript with a variety of fields as well as specific fields and methods?

In JavaScript, I can achieve this using the following code: var obj = { get(k) { return this[k] || ''; }, set(k, v) { this[k] = v; return this; } }; obj.set('a', 'A'); obj.get('a'); // returns &ap ...

Encounter the error message "Unable to resolve all parameters" after including the Interceptor

Currently, I am in the process of implementing HttpInterceptor functionality. However, upon adding it to @NgModule, I encountered the following error message in Chrome: Uncaught Error: Can't resolve all parameters for JwtInterceptor: (?, ?). at s ...

How to successfully extract and understand JSON data in Angular that has been delivered from a Spring controller

I am facing a unique challenge while trying to utilize JSON data obtained from a Spring API to populate a list in Angular. Within the datasets-list.component.ts file, I have the following code: import { Component, OnInit } from '@angular/core'; i ...

Looking to include a badge within the nebular menu

Can someone assist me with adding a badge to the Nebular menu to display the inbox count dynamically? Any help would be greatly appreciated. Thanks! import { NbMenuItem } from '@nebular/theme'; export const MENU_ITEMS: NbMenuItem[] = [ { ti ...