1

我有一个 API 类:

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 类:

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方法this.api.put上没有找到ApiService。自从我实例化之后我不ApiService明白this.api

4

1 回答 1

2

实际上,您可以通过依赖注入将实例ApiService放入其中:AccountService

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

您只需要注册这两个服务:

bootstrap(AppComponent, [AccountService, ApiService]);

否则我看不出有什么理由不能使用from 的put方法。ApiServiceAccountService

希望它可以帮助你,蒂埃里

于 2016-01-22T13:33:29.543 回答