Having trouble accessing a custom factory within a directive in Angular using TypeScript

Having some trouble with my injected storageService. When trying to access it in the link function using this.storageService, I'm getting an undefined error.

Any assistance on this issue would be greatly appreciated.

module App.Directive {
  import Services = Core.Services;
  import Shared = Core.Shared;
  export class UserNav implements ng.IDirective {
    restrict = 'A';
    require: any = "^?ngModel";
    scope = true;
    templateUrl: any = "template/user-nav.html";
    link: ng.IDirectiveLinkFn = function(scope, element, attributes, ngModel: any) {
        var a = this.storageService.getItem("userInfo", false);
        console.log("fetching > " + a);
    }
    constructor(public routerService: Services.RouterService,
        public storageService: Services.StorageService) {
    }
    static factory(): any {
        var directive = (routerService: Services.RouterService,
            storageService: Services.StorageService) => {
            return new UserNav(routerService, storageService);
        }
        directive['$inject'] = ['routerService', 'storageService'];
        return directive;
    }
  }
}

Answer №1

So the issue lies in the link function Change:

module App.Directive {
  import Services = Core.Services;
  import Shared = Core.Shared;
  export class UserNav implements ng.IDirective {
    restrict = 'A';
    require: any = "^?ngModel";
    scope = true;
    templateUrl: any = "template/user-nav.html";
    link: ng.IDirectiveLinkFn = function(scope, element, attributes, ngModel: any) {
        var a = this.storageService.getItem("userInfo", false);
        console.log("getting > " + a);
    }
    constructor(public routerService: Services.RouterService,
        public storageService: Services.StorageService) {
    }
    static factory(): any {
        var directive = (routerService: Services.RouterService,
            storageService: Services.StorageService) => {
            return new UserNav(routerService, storageService);
        }
        directive['$inject'] = ['routerService', 'storageService'];
        return directive;
    }
  }
}

To:

module App.Directive {
  import Services = Core.Services;
  import Shared = Core.Shared;
  export class UserNav implements ng.IDirective {
    restrict = 'A';
    require: any = "^?ngModel";
    scope = true;
    templateUrl: any = "template/user-nav.html";
    link(scope, element, attributes, ngModel: any) {
        var a = this.storageService.getItem("userInfo", false);
        console.log("getting > " + a);
    }
    constructor(public routerService: Services.RouterService,
        public storageService: Services.StorageService) {
    }
    static factory(): any {
        var directive = (routerService: Services.RouterService,
            storageService: Services.StorageService) => {
            return new UserNav(routerService, storageService);
        }
        directive['$inject'] = ['routerService', 'storageService'];
        return directive;
    }
  }
}

UPDATE: The previous solution doesn't work. This is because the link function acts as a callback and this refers to the global object. To address this, you need to declare the services as variables inside your module so they can be accessed through scope. Check out my fiddle for an example: see my fiddle

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

After using apt to install tsc, I find myself in a dilemma on how to either delete or upgrade it

After realizing I was missing Typescript on my server, I attempted to run the 'tsc' command. However, I received a message suggesting I use 'apt install tsc' instead. Without much thought, I executed the command. Normally, I would insta ...

Toggle the Editable Feature in AngularJS JSON Editor

Currently, I'm utilizing a library called ng-jsoneditor that is available on GitHub. I am attempting to switch the state of an element from being editable to being read-only. To indicate that an element should be read-only, I need to specify the onE ...

Can the concept of partial class be used in an AngularJS controller?

Is it possible to organize code into groups using partials in angularjs? The issue is that my controller has become too cluttered with a lot of code for different methods and functionalities, making it difficult to read. I want to maintain the same contro ...

1. Common obstacles in the functionality of data binding2. Constraints

Working on a basic controller to perform some calculations, which is a simplified version of a more complex project. The issue I'm facing is that the result displayed in the HTML gets recalculated every time there's a change, but when calculating ...

Tips for invoking an Android function from an AngularJS directive?

I am facing an issue with my HTML that uses an AngularJS directive. This HTML file is being used in an Android WebView, and I want to be able to call an Android method from this directive (Learn how to call Android method from JS here). Below is the code ...

Activate automatic selection when the input field is disabled

How can I enable auto-select for text in an input field even when it is disabled? Currently, the auto select feature doesn't work when the field is disabled. Here is my HTML: <input type="text" class="form-control" ng-model="gameId" select-on-cli ...

Convert the union into a mapped structure

Starting with the given Union type: type Union = { type: 'A', a: string } | { type: 'B', b: number } The end goal is to transform it into this MappedUnion type: type MappedUnion = { A: { type: 'A', a: string } B: { ...

Asynchronous execution of Angular 2 services

Currently, I am working on a project that utilizes Angular and RxJS. My approach involves creating an injectable class responsible for fetching data from a JSON source as shown below: import {Injectable, Inject} from '@angular/core'; import {Ht ...

Using the Angular Slice Pipe to Show Line Breaks or Any Custom Delimiter

Is there a way in Angular Slice Pipe to display a new line or any other delimited separator instead of commas when separating an array like 'Michelle', 'Joe', 'Alex'? Can you choose the separator such as NewLine, / , ; etc? ...

Utilizing Database values in .css files with Vue.js and TypeScript

I am currently working on extracting a color value from the database and applying it to my external .css files. I have searched extensively online but haven't found a satisfactory solution yet. Here is the JavaScript code snippet: createBackgroundHead ...

Tips for setting up a full-size image with nextJS and the <Image /> component

Upgrading NextJS to the latest version has resulted in some errors when using the Image component: // import Image from 'next/image' <div style={Object.assign({}, styles.slide, style)} key={key}> <Image src={src} alt="&quo ...

What is the proper way to declare and utilize a constant list within a component template in NuxtJs?

Can someone help me with using itemList in a template? The itemlist is a static list, but I am unsure of where to declare it and how to export it to the template. <template> <table class="table table is-striped is-narrow is-fullwidth" ...

Service function in Angular 2 is returning an undefined value

There are two services in my project, namely AuthService and AuthRedirectService. The AuthService utilizes the Http service to fetch simple data {"status": 4} from the server and then returns the status number by calling response.json().status. On the ot ...

The request/response is missing property "x" in type "y" but it is required in type "z" during fetch operation

I have configured an interface specifically for utilization with an asynchronous function: interface PostScriptTagResponse { script_tag : { readonly id : number , src : string , event : string , readonly created_at : string , readonl ...

I was directed to https://code.angularjs.org/ due to an error in the AngularJS injector

Currently, I am utilizing angularjs and gulp for real-time updates when making changes. However, each time I encounter an error, I am redirected to https://code.angularjs.org/ to read about the specific error. Instead of having to constantly click on the ...

Harness the power of ng-click in conjunction with data-ng-href for a

I am attempting to create a button that takes the user to the product details while also having the ability to increase a counter using an ng-click function. <div class="row center-block save-button" > <a data-ng-href="/savings/{{saving._id}} ...

Angular 4's Mddialog experiencing intermittent display problem

While using MDDialog in my Angular app, I've encountered a couple of issues. Whenever a user clicks on the div, flickering occurs. Additionally, if the user then clicks on one of the buttons, the afterclose event is not triggered. Can anyone provide ...

Achieving TypeScript strictNullChecks compatibility with vanilla JavaScript functions that return undefined

In JavaScript, when an error occurs idiomatic JS code returns undefined. I converted this code to TypeScript and encountered a problem. function multiply(foo: number | undefined){ if (typeof foo !== "number"){ return; }; return 5 * foo; } ...

Seeking assistance with downloading a collection of images as a zipped file using AngularJS

My code was previously working with jszip 2x but now I'm getting an error stating "This method has been removed in JSZip 3.0, please check the upgrade guide.". Even after following the upgrade guide, my code is still not functioning properly. I need a ...

What is the best way to efficiently filter this list of Outcome data generated by neverthrow?

I am working with an array of Results coming from the neverthrow library. My goal is to check if there are any errors in the array and if so, terminate my function. However, the challenge arises when there are no errors present, as I then want to destructu ...