我正在尝试在另一个类中使用我的ApiService类(处理api请求),但无法使其正常工作。
问题在于ApiService构造函数需要HttpClient,这意味着我不能只使用以下内容:http = new ApiService(new HttpClient(),globals)
ApiService:
import { Injectable } from '@angular/core';
import { HttpClient, HttpRequest } from '@angular/common/http';
import { Globals } from './globals';
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient, private globals: Globals) {}
get(url : string, params: {}){
return this.http.get(this.globals.api_url.concat(url), {params: params});
}
...
}
类调用ApiService:
export class UploadAdapter {
http: ApiService;
constructor() {}
upload() {
//Here I get an error saying can't get post of undefined
http.post('api_url'.concat('/medias/upload'), {}, {})
.subscribe((data) => {
//do stuff here.
});
}
}
答案 0 :(得分:1)
您没有将服务注入您的组件中
您的UploadAdapter
构造函数应该像这样
constructor(private http: ApiService) {}
还需要使用
this.http.post
代替
http.post