Search code examples
angularjsangulardependency-injectionng-upgrade

How to inject downgraded Angular service into an AngularJS project?


I have been following the guide here for upgrading an angularjs project.

However, the code base I really want to upgrade already has ts classes for a majority of services so I followed the official guide that replaces the angularjs phone service with a ts class. So now I have a ts class for the phone service, but when I run the application with ng serve the phone service is an unknown provider.

  • I have tried adding "types": ["angular"] to my tsconfig.
  • I have tried declaring angular in the service file
import { Injectable } from "@angular/core";
import { Observable } from "rxjs";
import { HttpClient } from "@angular/common/http";
import { IPhoneData } from "../../interfaces/IPhoneData";

// angular does not get resolved during compilation this way
// declare var angular: angular.IAngularStatic;

// Phone is an unknown provider this way
declare var angular: any;

import { downgradeInjectable } from '@angular/upgrade/static';

@Injectable()
export class Phone {
  constructor(private http: HttpClient) { }
  query(): Observable<IPhoneData[]> {
    return this.http.get<IPhoneData[]>(`phones/phones.json`);
  }
  get(id: string): Observable<IPhoneData> {
    return this.http.get<IPhoneData>(`phones/${id}.json`);
  }
}

angular.module('core.phone')
  .factory('phone', downgradeInjectable(Phone));

How can I get the phone service ts class injected into an angularjs component? Link to my repo.


Solution

  • Somewhere along the line I lost the case of the 'Phone' factory, it should have been like below (also the Observables should have been promises).

    export class Phone {
      constructor(private http: HttpClient) { }
      query(): Promise<IPhoneData[]> {
        return this.http.get<IPhoneData[]>(`phones/phones.json`).toPromise();
      }
      get(id: string): Promise<IPhoneData> {
        return this.http.get<IPhoneData>(`phones/${id}.json`).toPromise();
      }
    }
    
    angular.module('core.phone')
      .factory('Phone', downgradeInjectable(Phone));