注入服务的问题

Problems with inject in service

我有一个 Angular2 应用程序,我在其中创建了一个服务。现在我想扩展服务以从 Web API 获取一些数据。我遵循了 angular 团队的开发人员指南: https://angular.io/docs/ts/latest/guide/server-communication.html

阅读关于注入服务的优秀指南: http://blog.thoughtram.io/angular/2015/09/17/resolve-service-dependencies-in-angular-2.html

但我一直收到同样的错误:

Cannot resolve all parameters for 'UserService'(?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'UserService' is decorated with Injectable.

我在 boostrap 中添加了两个提供:

import "zone.js/dist/zone.min.js";
import "reflect-metadata";
import 'rxjs/Rx';
import { HTTP_PROVIDERS }    from 'angular2/http';
import { bootstrap } from "angular2/platform/browser";
import { UserService } from '../userservice';
import { PublicappComponent } from './publicapp.component';

bootstrap(PublicappComponent, [HTTP_PROVIDERS, UserService]);

这是我的简单 UserService.ts:

import {Injectable}     from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Observable}     from 'rxjs/Observable';
import {Headers, RequestOptions} from 'angular2/http';
import {UserModel}      from './usermodel';

@Injectable()
export class UserService {
    constructor(http: Http) { }
    private url = 'api/user';
}

我在 Angular2 周围使用 jspm。

您是否将 http.dev.js 文件包含在您的 HTML 条目文件中:

(...)
<script src="https://code.angularjs.org/2.0.0-beta.7/angular2.dev.js"></script>
<script src="https://code.angularjs.org/2.0.0-beta.7/http.dev.js"></script>

编辑

由于 Jspm 允许实现基于 ES6 的 Angular2 应用程序(而非 TypeScript),因此您不能使用方法参数级别的类型。所以你需要为parameters字段添加一个静态的getter:

@Injectable()
export class UserService {
  private url = 'api/user';

  constructor(http) { }

  static get parameters() {
    return [[Http]];
  }
}

有关详细信息,请参阅此插件:https://plnkr.co/edit/ymSUUCvG5NFvmCGqzj2r?p=preview