Developing an exportable value service type in TypeScript for AngularJS

I have been working on creating a valuable service using typescript that involves a basic switch case statement based on values from the collection provided below

 [{
     book_id: 1,
     year_published: 2000
   },
   {
     book_id: 2,
     year_published: 2003
    },
    {
      book_id: 3,
      year_published: 2007
   }]

The logic behind my value is quite simple

module app.values {

    export function getAge(year){
        let yearDef = null;
        switch(true){
            case (year > 2003):
            yearDef = 'Older than 2003';
            break;
            case(year < 2003):
            yearDef = "Younger than 2003";
            break;
            default:
            yearDef = "It's 2003";
        }
    }

    angular.module("app").value('yearDefService',{
       getAge: getAge
   });

}

In my controller, I am facing some challenges and not sure about the correct approach. The implementation seems to be failing as I haven't created an interface for the getAge method, leading to uncertainties on how to call it in the constructor.

 // Omitting controllers interface 
 static $inject = ["dataService","yearDefService"];
    constructor(public dataService    : app.factory.IDataService,
                public yearDefService : any,
                public getYear         :any
    ){

        var vm = this;
        vm.yearThing = dataService.getAllYearThings();
        vm.getAge = yearDefService.getAge;

       ....

When viewing the result on the UI

<ul ng-repeat="year in vm.yearThing">
  <li> <b> Year Definition: </b> {{ vm.getAge(year.year_published) }} </li>
</ul>

Unfortunately, the output appears empty and console.log returns undefined. It seems like I may have made mistakes in the implementation. Any guidance or assistance would be truly appreciated.

Answer №1

Your switch statement may be incorrect:

export function getAge(year){
        let yearDef = null;
        switch(true){
            case (year > 2003):
            yearDef = 'Older than 2003';
            break;
            case(year < 2003):
            yearDef = "Younger than ";
            break;
            default:
            yearDef = "It is 2003";
        }
    }

A switch cannot operate on expression cases, and the function getAge will not return anything, leading to undefined. Revise it to something like this:

export function getAge(year) {
  if(year > 2003) {
    return 'Older than 2003';
  } else if(year < 2003) {
    return 'Younger than ';
  } 
  
  return 'It\'s 2003!';
}

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

best method for implementing a TypeScript object

I've been searching high and low, but I can't seem to find the exact answer I need. Please inform me if my question has already been asked. My goal is to construct an object in TypeScript that includes attributes of custom types. The issue I&ap ...

Guide on verifying if a variable is a tuple in TypeScript

I am attempting to determine if a variable passed to a function, which can either be an array of numbers or an array of tuples, is the array of tuples. function (times: Array<number> | Array<[number, number]>) { if (Array.isArray(times[0]) ...

The object literal is restricted to defining existing properties, and 'id' is not a recognized property in the type 'FindOptionsWhere<Teacher>'

I encountered a persistent error within my teachers.service: Object literal may only specify known properties, and 'id' does not exist in type 'FindOptionsWhere | FindOptionsWhere[]'.ts(2353) FindOneOptions.d.ts(23, 5): The expected t ...

Searching and filtering through various objects using AngularJS ng-repeat

I have two array objects called user and test. I am using the ng-repeat directive on the test object along with a search filter, but it seems to only work for the test object and not the user object. Here is my code: <label>Search</label> & ...

what is the best way to eliminate comments from nested arrays when using useReducer?

Can someone help me figure out how to use useReducer and useContext to manipulate global state? I specifically need to know how to delete comments using useReducer. Data Structures View the interface image here Sample Data Array export const listsData:IDa ...

Gather information to present in a specialized layout

i have two mysql tables order and orderitems. now i want to showcase this information using AngularJS on a separate screen. My table structure: Table order includes id, table_id, date_time Table orderitems has order_id, food_item, item_qty, deliver ...

Exploring the connection between divs in a layout using CircosJS

I am new to d3js and I am exploring the use of a module called circosJS. Currently, I have created a plunker to showcase what I am struggling with: Plunker Link My main concern is how can I connect months together? Below is a snippet of my JavaScript co ...

Error with TypeScript Compiler in Angular 2

Currently, I am facing an issue while trying to run tsc in my Angular 2 application directory. The error message I receive is: Error TS5023: Unknown compiler option 'moduleResolution'. This issue seems to be hindering the startup process, as ts ...

What is the best method to change the value of a nearby TD text box?

I am currently developing a shopping cart application that requires me to update product screens based on users' previous orders stored as local JSON data. The product screen is built using JSON returned from the server. My goal now is to automatical ...

Directive removing input field value from

I'm facing a straightforward Angular issue - it seems like I can't see the solution clearly. The problem arises when I attach a directive to an input field. The intention is to compare new data with old data and display a popup. However, once I ...

Combining two JSON datasets and presenting the merged information

I need help parsing two sets of json data from the following URLs: https://raw.githubusercontent.com/openfootball/football.json/master/2015-16/en.1.json https://raw.githubusercontent.com/openfootball/football.json/master/2016-17/en.1.json My goal is to di ...

Navigating through the Angular Upgrade Roadmap: Transitioning from 5.0 to 6

As per the instructions found in this helpful guide, I executed rxjs-5-to-6-migrate -p src/tsconfig.app.json. However, an error is appearing. All previous steps were completed successfully without any issues. Any suggestions on how to resolve this? Please ...

AngularJS ng-click incompatibility causing non-functioning popover content

I've gone through all the posts regarding this issue, but unfortunately, none of them proved to be helpful. It seems that the jsfiddle and plunker links provided are no longer functioning as expected. My objective is quite simple - I want to place a ...

`Incorporate concurrent network requests in React for improved performance`

I am looking to fetch time-series data from a rest service, and currently my implementation looks like this async function getTimeSeriesQuery(i) { // Demonstrating the usage of gql appollo.query(getChunkQueryOptions(i)) } var promises = [] for(var i ...

A step-by-step guide on assigning values to an Angular Material Auto Complete component in Angular 7

Hey there! I'm currently using the Angular Material Auto complete component in my Angular 7 app and I'm trying to find a way to bind a value from an API response to it. Can someone help me out with a solution for this? HTML: <mat-form-field> ...

Ways to confirm non-null values and bypass the row if it is

I have been attempting to compare 2 dates in order to appropriately display data in a table. I have tried the following approach: ${this.dateToCompare.getTime()} > ${row.CreateDate.getTime()} However, there is an issue where CreateDate has a null value ...

Faulty deduction can occur when implementing the return statement in an identity function, or when incorporating an optional parameter

Encountering strange behavior while working on identity functions in a wizard system schema. Using a constrained identity function for inference is causing issues with one property that cannot be inferred when using the following: When the return value fr ...

Combining TypeScript and JavaScript for efficient mixins

I came across an article on MDN discussing the usage and creation of mix-ins (link). Intrigued, I decided to try implementing it in TypeScript: type Constructor = new (...args: any) => any; function nameMixin(Base: Constructor) { return class extends ...

Turn off the interconnected route while utilizing npm to display the tree of dependencies

If I want to display the project's dependencies tree using npm, I would use the following command: npm ls lodash The output will look something like this: > npm ls lodash npm info using [email protected] npm info using [email protected] ...

What is the best way to sort a union based on the existence or non-existence of a specific

My API response comes in the form of a IResponse, which can have different variations based on a URL search parameter. Here is how I plan to utilize it: const data1 = await request<E<"aaa">>('/api/data/1?type=aaa'); const d ...