angular - 如何在不使用构造函数的情况下实例化 Angular 2 服务?
问题描述
我正在尝试在另一个类中使用我的 ApiService 类(处理 api 请求),但无法使其正常工作。
问题是 ApiService 构造函数需要 HttpClient,这意味着我不能只使用类似的东西:http = new ApiService(new HttpClient(), globals)
api服务:
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.
});
}
}
解决方案
您没有在组件中注入服务
你的UploadAdapter
构造函数应该是这样的
constructor(private http: ApiService) {}
你还需要使用
this.http.post
代替
http.post
推荐阅读
- php - 新创建的 PHP Codeception 项目正在运行,没有错误输出
- ruby - 有没有办法在不使用 3 个收集器来组合字符串的情况下重构它?
- excel - 在 Excel 上创建一组合并的对
- python - 使用迭代器创建正则表达式模式
- responsive-design - CSS 打破媒体内容而不是屏幕大小
- clickhouse - Clickhouse:滑动/移动窗口
- jq - jq + 运算符是否渴望?
- pandas - 基于可互换出现在两列中的值聚合数据?
- java - 类、接口或枚举预期 2 个错误
- javascript - 如何在页面加载后注入的 HTML 中使用 VueJS?