【问题标题】:How to inject downgraded Angular service into an AngularJS project?如何将降级的 Angular 服务注入 AngularJS 项目?
【发布时间】:2019-06-14 01:46:16
【问题描述】:

我一直在按照指南 here 升级 angularjs 项目。

但是,我真正想要升级的代码库已经为大多数服务提供了 ts 类,所以我遵循了official guide,它用 ts 类替换了 angularjs 电话服务。所以现在我有一个电话服务的 ts 类,但是当我使用 ng serve 运行应用程序时,电话服务是一个未知的提供者。

  • 我已尝试将 "types": ["angular"] 添加到我的 tsconfig。
  • 我已尝试在服务文件中声明 Angular
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));

如何将电话服务 ts 类注入到 angularjs 组件中?链接到my repo

【问题讨论】:

    标签: angularjs angular dependency-injection ng-upgrade


    【解决方案1】:

    在某处我丢失了“电话”工厂的案例,它应该如下所示(Observables 也应该是承诺)。

    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));
    

    【讨论】:

      猜你喜欢
      • 2016-12-09
      • 1970-01-01
      • 2021-07-23
      • 2019-09-05
      • 1970-01-01
      • 2018-10-27
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多