Ionic2 - 将服务与 TabsPage 一起使用会破坏应用程序,导致启动时出现运行时错误

Ionic2 - Reusing Service with TabsPage breaks app, causes runtime error on startup

我是 Ionic2 的新手,遇到了一个错误,该错误似乎是一个我无法理解的页面的循环依赖。

Error: Can't resolve all parameters for HiredJobsPage: (?).

为了找出问题所在,我将我的代码精简到最基本的部分;跟TabsPage有点关系。

我正在使用 Ionic2 的选项卡模板项目,其中有一个 tabs.ts 文件。此文件指定要在页面底部显示的 3 个选项卡,每个选项卡都链接到另一个页面。

import { Component } from '@angular/core';

import { JobRequestsPage} from '../job-requests/job-requests';
import { HiredJobsPage } from '../hired-jobs/hired-jobs';
import { ProfilePage } from "../profile/profile";

@Component({
  templateUrl: 'tabs.html'
})
export class TabsPage {
  // this tells the tabs component which Pages
  // should be each tab's root Page
  tab1Root: any = ProfilePage;
  tab2Root: any = JobRequestsPage;
  tab3Root: any = HiredJobsPage;

  constructor() {

  }
}

我还有一个非常基本的服务,除了将 TabsPage 的实例分配给局部变量外什么都不做。

import {Injectable} from '@angular/core';
import {TabsPage} from "../../pages/tabs/tabs";

@Injectable()
export class MyService {

  foo: any = TabsPage;

  constructor() {

  }
}

此服务工作正常,当 MyService 仅注入一个组件时,项目编译并 运行s。但是,当我将服务注入两个组件时,项目中断并且不会 运行。如果我将另一个页面(ProfilePage、JobRequests、null 等)分配给 foo 变量,一切都很好;只有 TabsPage 导致错误。为什么会这样?

查看 angular dependency injection and forward reference in particular.Another blog post is here

This service works fine, and the project compiles and runs, when MyService is injected into only one component. However, when I inject the service into two components, the project breaks and won't run. If I assign another page (ProfilePage, JobRequests, null, etc.) into the foo variable, things are fine; it is only TabsPage which causes the error.

您的标签页(T) 指的是类:P、J 和H。 服务(S)指的是T.

     T        S
    /|\       |
   / | \      |
  P  J  H     T

根据您选择注入服务的 类,您最终将循环依赖指向选项卡页面 (T)。 一种解决方案是在注入服务时使用前向引用。

constructor(@Inject(forwardRef(() => MyService )) myService)