Transform Promise<any> into a designated type failure

Beginner inquiry concerning typescript/angular4+/ionic4. I have a service set up to make backend REST calls, and based on the response received, I need to store that data in local storage for future reference. However, I am encountering a type conversion error. Any advice would be appreciated.

 this.locationService.saveLocationNew(this.newLocation).subscribe(res=> {
     this.locationInfo = res;
     console.log('Response from backend'+ this.locationInfo);
     this.storage.set(StorageKeys.LOCATION_DATA, this.locationInfo);
     this.locationInfo = null;
     this.locationInfo = <AddLocationResponse>this.storage.get(StorageKeys.LOCATION_DATA); --> Error occurs here.
   });

This is how my service is structured:

 saveLocationNew(request: AddLocationData): Observable<AddLocationResponse> {
      return this.httpClient.post<AddLocationResponse>(this.addLocationUrl, request , { headers: Constants.createHeader()}); --> I follow a different approach without using then and mapping responses to res.json, as it's not necessary in Ionic4
 }

Answer №1

Check out this code snippet

 this.locationService.saveLocationNew(this.newLocation).subscribe(async (response)=> {
     this.locationInfo = response;
     console.log('Response from backend'+ this.locationInfo);
     this.storage.set(StorageKeys.LOCATION_DATA, this.locationInfo);
     this.locationInfo = null;
     const data = await <AddLocationResponse>this.storage.get(StorageKeys.LOCATION_DATA).catch((error) => 'return anything you want');
     if (data) {
       this.locationInfo = data;
     }
   });

Answer №2

Validate type using TypeError

function checkIfAnimalOrHuman(toBeChecked: PersonOrAnimal): toBeChecked is Animal {
  if((toBeChecked as Animal).type){
    // perform actions
  }
   throw new TypeError('Object is not an Animal');
}

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

Fetching Form Data from Angular Service

My project structure consists of a FATHER component with a stepper, each step-page containing a CHILD component with a FORM. In one page, the CHILD component has another CHILD with yet another FORM. At the final step of the stepper, there is a SUBMIT butt ...

"Prior to authenticating the user, the Angular route guard is triggered

A route guard was successfully implemented to redirect users to the login page if they are not authenticated, with the login check being of type Observable. Everything works fine when a user is logged in and navigates to a protected page: { path: 'pr ...

Is it possible to retrieve the precise key currently indexed within type declaration?

I am currently working on developing a simple type that would require a nested object key to reference the outer level. For better understanding, let's take an example: const obj = { foo: { name: 'bar', ref: 'foo' // & ...

In TypeScript, enhancing an interface with additional properties

Currently, I am working on an Angular project and have developed this interface to display some data: export interface UserData { name: string, vorname: string, strasse: string, plz: string, ort: string, handynummer: string, telefonnummer: s ...

Issues with Angular's *ngIf directive not functioning correctly

Within my template, I have a block of HTML that controls the visibility of a div. <div *ngIf="csvVisible"> <p>Paragraph works</p> </div> This particular code snippet belongs to my component. export class SettingsComponent imple ...

What is the best way to outline this model using typescript?

Here is a JSON model that I am working with: { "loggers" : { "logger1" : { "name" : "logger1", "level" : "DEBUG", "sub_loggers" :{ "logger1.nested_logger1" : { "name": "lo ...

Ways to trigger re-validation of a field in an angular reactive form

Currently, I am working with Angular and utilizing reactive forms along with material UI. One scenario that I have encountered is having a form field that should only be required if another specific field has been selected - such as displaying a text input ...

The issue with launching a Node.js server in a production environment

I'm currently facing an issue when trying to start my TypeScript app after transpiling it to JavaScript. Here is my tsconfig: { "compilerOptions": { "module": "NodeNext", "moduleResolution": "NodeNext", "baseUrl": "src", "target": " ...

Mastering the art of theming components using styled-components and Material-UI

Can you integrate the Material-UI "theme"-prop with styled-components using TypeScript? Here is an example of Material-UI code: const useStyles = makeStyles((theme: Theme) => ({ root: { background: theme.palette.primary.main, }, })); I attemp ...

The window:beforeunload event in IE 11 always triggers the unsaved changes dialogue box

When it comes to adding a listener for the beforeunload event on the global window object, IE 11 behaves differently compared to Chrome and Firefox. This is particularly noticeable when using Angular's "ngForm" module. If a form is dirty and has not ...

Using Angular 2 to convert and display data as a particular object type in

I have recently developed a basic application using the Angular2 tutorial as my guide. Initially, I established a straightforward "Book" model: /** * Definition of book model */ export class Book { public data; /** * Constructor for Book ...

Discovering the highest value within an array of objects

I have a collection of peaks in the following format: peaks = 0: {intervalId: 7, time: 1520290800000, value: 54.95125000000001} 1: {intervalId: 7, time: 1520377200000, value: 49.01083333333333} and so on. I am looking to determine the peak with the hig ...

Exploring the filter method in arrays to selectively print specific values of an object

const array = [ { value: "Value one", label: "Value at one" }, { value: "Value 2", label: "Value at 2" }, { value: "" , label: "Value at 3" } ...

Tips for executing an operation based on multiple observables in Angular

I need to create a functionality where upon clicking a button, a file containing a specific user's data is exported. The user's identity is stored in an observable (user$). If the user is not authorized to access this data, they should be redirec ...

Tips for ensuring a method is not invoked more than once with identical arguments

I'm grappling with a challenge in JavaScript (or typescript) - ensuring that developers cannot call a method multiple times with the same argument. For instance: const foo = (name: string) => {} foo("ABC") // ok foo ("123") ...

Is it possible for TypeScript to convert objects while preserving type annotations?

Apologies for my limited English skills, but I will do my best to explain my dilemma. I am looking to create a TypeScript function that can replace the keys of an Object. For example: interface Target { name: string; ID: number; } // The functio ...

Exploring Angular Components with Jasmine and Karma while integrating third-party tools such as ExcelJS

Currently tackling the challenge of writing tests for a project using ExcelJS. The project runs smoothly in both build and production environments, but when attempting to incorporate unit tests for certain components, I'm encountering issues with Test ...

Can you showcase two distinct perspectives on a single page?

One of my components has nested ngFor directives looping through an array of users and their posts. I have a view link within this element, and when clicked, it should show detailed information about both the user and the post. However, the current setup i ...

Some font-awesome icons are not appearing on the screen

As a beginner in web design, I am experimenting with using font awesome icons in Angular 9 projects within list items. While some of the icons are displaying properly, others are not. You can see the issue in the attached image. To access the icons, I have ...

Locate a user within an array in Angular 5 by inputting a specific character into a textarea before initiating the search

I'm currently facing a situation with my textarea component... <textarea [(ngModel)]="message" id="commentBox" placeholder="Add your comment here..."></textarea> Additionally, I have a user list that retrieves data from an external API l ...