我有一個API類:不含http角2類在構造參數
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
這是完全不清楚你試圖完成什麼。如果你需要'Http'來發出請求,那麼你怎麼真的希望它傳遞給'ApiService'?你爲什麼不想讓'Http'被DI傳遞? –
完全清楚他想要什麼。我自己也有同樣的問題。 –