Angular 2 class 构造函数参数中没有 Http

Angular 2 class without Http in the constructor parameters

我有一个 API class:

export class ApiService {

  constructor(public http: Http) { }

  put(controller: string, method: string, data: Object) {

    return this.http.put("http://127.0.0.1:8000",
      JSON.stringify(data), {
      })

    .map(res => res.json())

    .catch(err => {
      return Observable.throw(err.json());
    });

  }

}

和一个 AccountService class:

export class AccountService {

  api: ApiService;

  constructor() {
    this.api = new ApiService();
  }

  login(username: string, password: string) {

    return this.api.put("accounts", "login", { username: username, password: password});

  }

}

然而当我运行这个例子有两个问题:

1) ApiService 需要在构造函数中使用 http。因此 this.api = new ApiService(); 应该提供 Http 这不是我想要的。

如何修改 ApiService 以便我不必向构造函数提供 Http

2) 在 AccountService 中,在 ApiService 中找不到 this.api.put 方法。我不明白,因为我将 ApiService 实例化为 this.api

实际上,您可以通过依赖注入将 ApiService 的实例获取到 AccountService 中:

export class AccountService {
  constructor(private api: ApiService) {
  }
}

您只需注册这两项服务:

bootstrap(AppComponent, [AccountService, ApiService]);

否则,我看不出有什么理由不能使用 AccountServiceApiServiceput 方法。

希望对你有帮助, 蒂埃里