Unable to retrieve a string from one function within another function

Three functions are responsible for triggering POST API calls, with the intention of returning a success or failure message to whoever invokes them (Observable<string>).

In an effort to avoid repetition, I introduced a new function to retrieve success messages. However, this new implementation seems to be causing issues as when I call getSuccessMessage, the app displays a blank page. Interestingly, using a regular string ("Something") in its place works as expected.

Here are the functions in question:

export enum ListType {Cars, Animals, Books}

 public updateOne(carList: Car[]): Observable<string> {
    return this._myApiSevice.postCarsNewOrder(carList)
      .map(response => this.getSuccessMessage(ListType.Cars)) //update succeeded  
      .catch(error => Observable.of("FAILURE: post to Cars did not succeed!")); 
  }

  public updateTwo(animalList: Animal[]): Observable<string> {
    return this._myApiSevice.postAnimalsNewOrder(animalList)
      .map(response => this.getSuccessMessage(ListType.Animals))
      .catch(error => Observable.of("FAILURE: post to Animals did not succeed!"));
  }

  public updateThree(bookList: Book[]): Observable<string> {
    return this._myApiSevice.postBooksNewOrder(bookList)
      .map(response => this.getSuccessMessage(ListType.Books)) //update succeeded
      .catch(error => Observable.of("FAILURE: post to Books did not succeed!"));
  }

  public getSuccessMessage(listType: ListType): string {
    return "SUCCESS: post to " + ListType[listType] + "succeed!";
  }

Do you notice anything wrong here?

This error is displayed in the console:

EXCEPTION: Error: Uncaught (in promise): Cannot resolve all parameters for 'MyCmp'(undefined, ElementRef, MdDialog). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'MyCmp' is decorated with Injectable.

The enum is declared in another class which is imported to access the enums.

If you have any suggestions on how to consolidate the failure message logic along with the success message into one function, I would greatly appreciate it. Thank you!

Answer №1

To extract the value of a string from an enum type in TypeScript, you must follow these steps:

enum ListType {
  Cars,
  Animals,
  Books
}
var booksStr = ListType[ListType.Books];

This concept is elaborated further in this link:

An example function illustrating the above would look like:

public getSuccessMessage(listType: ListType): string {
    return "SUCCESS: post to " + ListType[ListType.listType] + "succeed!";
}

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

Angular device redirection allows you to automatically redirect users based on the device

Currently in my Angular project, I am attempting to dynamically redirect users based on their device type. For example, if the user is on a Web platform, they will be redirected to www.web.com. If they are on an Android device, they should go to www.androi ...

Angular2: Issue with service injection within service

Below is the code snippet I have written. Assuming you can grasp the purpose without further elaboration. @Injectable() export class Dispatcher { } @Injectable() export class TodoStore { constructor(@Inject(Dispatcher) private dispatcher:Dispatcher ...

nodemon is launching an endless number of .node-xmlhttprequest-sync files

I am facing a strange issue with my app that imports a module containing a promise. Everything runs smoothly when I start the app using "node app.js" However, if I use "nodemon" to launch it, it constantly creates files with names like .node-xmlhttpreque ...

Error: React - Unable to access the 'lazy' property because it is undefined

I used a helpful guide on the webpack website to incorporate TypeScript into my existing React App. However, upon launching the app, an error message pops up saying: TypeError: Cannot read property 'lazy' of undefined The version of React being ...

A guide on transferring data to an external JavaScript script that is asynchronously loaded

I came across this solution on Stack Overflow here to load JavaScript asynchronously. However, I am wondering how can I pass some data to the external file? This is my current code: <script id="js-widget-o2ba1y" type='text/javascript'> ...

Creating multiple React applications using shared configuration files: A step-by-step guide

I am in the process of developing a React app, and my goal is to create multiple React apps that share the same configurations - including modules and configuration files like tailwind.config.cjs. How can I modify my environment to achieve this? My plan i ...

Troubleshooting a JavaScript project involving arrays: Let it pour!

I'm a beginner here and currently enrolled in the Khan Academy programming course, focusing on Javascript. I've hit a roadblock with a project called "Make it rain," where the task is to create raindrops falling on a canvas and resetting back at ...

Challenges with HTML and JavaScript

Struggling to get this code to work properly with Node.js. const express = require('express') const app = express() app.use(express.static('public')) //includes content of public folder app.get('/', function (req, res){ ...

What causes JavaScript to be unable to run functions inside other functions?

Functional languages allow functions to be executed within the argument brackets of nested functions. In JavaScript, which drew inspiration from Scheme, what is the equivalent? f( f ( f ( f))) console.log( 1 + 1 ) //2 How does JavaScript execut ...

Error: The initial parameter must be a string, Buffer, ArrayBuffer, Array, or Array-like Object. An object type was passed in instead in CryptoJS

In my quest to encrypt and decrypt data in react-native, I embarked on using the crypto node module by incorporating it into my react native project through browserify. While attempting encryption with the code snippet provided below, an error surfaces sta ...

Seeking a solution for resizing the Facebook plugin comments (fb-comments) using Angular when the window is resized

Is it possible to dynamically resize a Facebook plugin comment based on the window or browser size? I want the fb-comment div to automatically adjust its size to match the parent element when the browser window is resized. <div id="socialDiv" class="c ...

Issue with Ajax post redirection back to original page

I'm facing an issue with my ajax call where I send multiple checkbox values to a php file for processing and updating the database. The post request and database updates are successful, but the page doesn't return to the calling php file automati ...

The Vue pagination component is optimized to load a single page at a time

There seems to be an issue with my paginate component as it is only displaying the first page despite the total number of objects I want to show: https://i.sstatic.net/rEonp8Rk.png Pagination Component Code: <paginate v-if="searchResults.length & ...

Similar to the getState() function in react-redux, ngrx provides a similar method in Angular 6 with ngrx 6

Recently, I developed an application with react and redux where I used the getState() method to retrieve the state of the store and extract a specific slice using destructuring. Here's an example: const { user } = getState(); Now, I am transitioning ...

What is the best way to match the minimum height of one div to the height of another div?

I need to dynamically set the minimum height of #wrapper equal to the height of #sidebar, but the height of #sidebar is not fixed. Here is my attempt at achieving this with JavaScript: var sidebarHeight = jQuery('#sidebar').height; jQuery(&apos ...

Could we bypass the parent component somehow?

Just starting out with angular and decided to work on a small project. As I was setting up my routing, I encountered a problem. Here is the routing setup I have: const routes: Routes = [ {path: '', redirectTo: '/home', pathMatch: &a ...

Create a generic function that retrieves a specific property from an array of objects using the select method

Currently, I have implemented four functions that select entries from an array based on different properties. if ($scope.filters.filter1) $scope.filteredEntries = $scope.filteredEntries.filter(function (o) { return o.field1 === $scope.filt ...

An error is triggered by serializing a TinyBox POST form into an Array

When I implemented the code below, it performed as anticipated: TINY.box.show({url:target, post:$("form[name='currentSearch']").serialize(), width:650, mask:true, close:true, maskid:'boxMask', boxid:'popupBox', openjs:funct ...

Hide the address bar in a Google Maps iFrame

After numerous attempts, I still can't seem to hide the address bar on this Google Maps iFrame. Can anyone provide a solution or workaround for this issue? https://i.sstatic.net/x0pl9.png I have tried using display:none; in our CSS, which successfull ...

The issue with executing event.keyCode == 13 in Firefox remains unresolved

I've implemented a function that sends comments only when the "enter" key is pressed, but not when it's combined with the "shift" key: $(msg).keypress(function (e) { if (event.keyCode == 13 && event.shiftKey) { event.stopProp ...