Encountering an error message stating "Unable to access property 'injector' as null when attempting to downgrade Angular 2 service."

Hello everyone, I could use some assistance with a particular issue I'm facing.

Below is the code snippet from my angular 1.x app.js:

angular.module('app', []);

angular.module('app.test', ['app'])
    .config(($stateProvider) => 
        $stateProvider.state('base', {
                url: '/',
                controller: 'TestStateCtrl',
                resolve: {
                    authenticationCheck: ['angularNg1Service', angularNg1Service=> {
                        angularNg1Service.test1();
                    }]
                }
            })
        })
    .run((angularNg1Service) => {
        angularNg1Service.test2();

    });

Here is the code for my angularNg1Service:

    angular.module('app')
    .service('angularNg1Service',
        function (angularNg2Service} {
            //some code here 
}

The angularNg2Service is downgraded before the .run function of the angular 1.x module is executed:

window['angular']
        .module('app')
        .factory(
            'angularNg2Service',
            upgradeAdapter.downgradeNg2Provider(AngularNg2Service)
        );

However, I am encountering an error message:

Cannot read property 'injector' of null

This error occurs when the .run function of the angular 1.x module starts.

Below is my main.ts file:

import { upgradeAdapter } from './upgradeAdapter';
import { bootstrapNg1Components } from './app/ng1Components';    
bootstrapNg1Components(upgradeAdapter);// this function downgrades my AngularNg2Service

upgradeAdapter.bootstrap(document.querySelector('html'), ['app.start']);

I have searched for similar issues, but haven't been able to find a solution.

I have several Angular2 Services that are successfully downgraded. The problem seems to be isolated to one specific service that is injected into an Angular1 service used in the .run function.

Answer №1

If you encounter an issue, you can try this workaround explained in detail at https://github.com/angular/angular/issues/10992: insert your run code within a setTimeout function.

angular.module('app.test', ['app'])
...
    .run(($injector) => {
        setTimeout(function() {
           var angularNg1Service = $injector.get('angularNg1Service');
           angularNg1Service.doSmth();
           // downgraded angularNg2Service is available here
           // inside of async function that will run after module.run method
           var angularNg2Service = $injector.get('angularNg2Service');
        },0);
    });

To ensure the application state is not started before the application is configured (performed in the run method), you can add a resolve for every state.

angular.module('app.test', ['app'])
    .config(($stateProvider) => 
        $stateProvider.state('base', {
            url: '/',
            controller: 'TestStateCtrl',
            resolve: {
                appBootstrapped: ['appBootstrapStateService', () => {
                    return appBootstrapStateService.statePromise;
                ]},
                authenticationCheck: ['angularNg1Service', 'appBootstrapped', (angularNg1Service, appBootstrapped) => {
                    angularNg1Service.test1();
                }]
            }
        })
    })

To ensure it functions correctly, you need to change the bootstrapped state at the end of the module.run method.

angular.module('app.test', ['app'])
    ...
    .run(($injector) => {
        setTimeout(function() {
            ...
            var appBootstrapStateService = $injector.get('appBootstrapStateService');
            appBootstrapStateService.complete(); // allow state to work
        },0);
    });

appBootstrapStateService is an angularJS service similar to:

angular.module('app')
    .service('appBootstrapStateService', function () {
        const stateSubject = new Rx.Subject();
        this.statePromise = stateSubject.asObservable().toPromise();

        this.complete = () => {
            stateSubject.complete();
        };
    });

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

Encountered an issue while resolving symbol values statically within my exclusive set of modules

Encountered an error while resolving symbol values statically. The function 'DataModule' is not supported. Consider using a reference to an exported function instead of a function or lambda, resolving the symbol DataModuleRoot in E:/shopify-clien ...

Order of execution for Angular 2 components

import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; import {Router, ActivatedRoute, Params} from '@angular/router'; import { Country } from &ap ...

AngularJS does not allow data to be deleted in mongodb

Backend code: var User = require("./models/user"); var express = require('express'), app = express(), Account = require("./models/account"), mongoose = require('mongoose'), passport = require("passport"), basicAuth = require('basi ...

Unable to append item to document object model

Within my component, I have a snippet of code: isLoaded($event) { console.log($event); this.visible = $event; console.log(this.visible); this.onClick(); } onClick() { this.listImage = this.imageService.getImage(); let span = docu ...

Utilizing RxJs Observables in a service across various pages necessitates manual triggering of change detection

I have an observable in a shared service that is being used by multiple pages. The issue arises when the value of the observable is changed on one page and then I navigate to another page, as the subscription on the second page does not detect any change ...

Tips for limiting users to inputting only alphanumeric characters and excluding special characters in an input field using Angular 8

How can I prevent users from inputting special characters in an input field and only allow alphanumeric values? The code that I have implemented so far does not seem to be working as intended. When a user enters a special character, it still shows up in th ...

What could be causing the Angular imports to not function properly?

I've recently set up a project, and it's compiling successfully. However, every time I attempt to add a directive like [formGroup], it throws an error such as "Property formGroup is not provided by any applicable directives nor by form element". ...

Using Angular and Typescript to Submit a Post Request

I am working on a basic Angular and Typescript page that consists of just one button and one text field. My goal is to send a POST request to a specific link containing the input from the text field. Here is my button HTML: <a class="button-size"> ...

Issue with displaying value in AngularJS $scope

I am currently using flask(version 1.0.2) along with AngularJS (version 1.7.2) material (version 1.1.10). While the controller is properly attached to the view and functioning, it seems to be not displaying values in the view. This is the controller: $$ ...

Exploring the implementation of if/else statements in Sass/HTML

I need assistance with customizing the appearance of a save button on my form. The button is currently disabled and appears in blue color, but I would like it to change to a different color until all fields within the form are completed. Even though it c ...

Utilizing the Yelp API and/or the Google Places API for project development

Hey there! So I've been given a project for school that involves using either the Google Places API or Yelp API to allow users to search for local restaurants or bars near a specific location. I've spent the last couple of days researching how t ...

What is the best way to provide a parameter to the query function in an Angular service class?

This snippet of code was generated by jHipster. invoice.component.ts @Component({ selector: 'jhi-invoice', templateUrl: './invoice.component.html' }) export class InvoiceComponent implements OnInit, OnDestroy { loadAll() ...

Exploring Angular 9: Experimenting with iterating over a collection of objects and performing validations

Forgive me if this is a basic question, but I am new to Angular 9 and json. I am attempting to iterate through a list and only create a table row if the correct ID matches the ID passed from the previous page link. I am struggling to make the if statement ...

Tips for recognizing hyperlinks within a block of text and converting them to clickable links in Angular 2

My task is to create clickable links within a paragraph of strings. I tried using a custom pipe, but seem to be missing something essential. Here's my attempt: import { Pipe, PipeTransform } from '@angular/core'; import { DecimalPipe ...

Adding an ellipsis (...) at the end of a specific number of characters within AngularJS

My current project involves extracting educational data from Facebook and displaying it on my webpage. However, I have run into an issue with strings that are too long. I am looking for a solution to truncate the string after a certain number of characters ...

Sharing models between AngularJS controllers

I am currently in the process of developing an application that will showcase various charts and controls to filter the presented data. I have structured the HTML page in a way that remains consistent throughout, leading me to consider creating an HTML tem ...

Slider component designed for selecting ranges of letters in the alphabet using

Currently, I am working on creating a website using Angular for a school project. One feature I am experimenting with is a slider for selecting classes ranging from class 1 to class 5. The classes are stored in arrays, so when users slide to select a range ...

Accessing the parent scope from a directive within a nested ng-repeat in AngularJs

Seeking guidance on accessing the parent scope within a directive nested in an ng-repeat. Here is an example: <div ng-app="myApp" ng-controller="myCtrl"> <div ng-repeat="section in sections"> {{section.Name}} <div ng-rep ...

Navigating through Angular Material table elements

Currently, I am working with Angular Material's mat-table component and have noticed a unique notation used for loop properties such as *matCellDef, which is demonstrated in this Demo. In an attempt to streamline my code, I sought to dynamically gener ...

Issue with AngularJs Autocomplete: this.source is not being recognized as a function

Below is the HTML code snippet for an autocomplete textbox feature: <body ng-controller="HomeController" ng-init="init()"> <div class="col-xs-4 search-bar-position" > <form role="search" > <div c ...