如何在不使用构造函数的情况下实例化angular 2服务?
我正在尝试使用我的ApiService类处理另一个类中的api请求,但无法使其工作。 问题是ApiService构造函数需要HttpClient,这意味着我不能只使用如下内容:http=new-ApiServicenew-HttpClient,globals ApiService:如何在不使用构造函数的情况下实例化angular 2服务?,angular,typescript,Angular,Typescript,我正在尝试使用我的ApiService类处理另一个类中的api请求,但无法使其工作。 问题是ApiService构造函数需要HttpClient,这意味着我不能只使用如下内容:http=new-ApiServicenew-HttpClient,globals ApiService: import { Injectable } from '@angular/core'; import { HttpClient, HttpRequest } from '@angular/common/http';
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});
}
...
}
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.
});
}
}
类调用服务:
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});
}
...
}
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构造函数应该如下所示 constructorprivate http:ApiService{} 您还需要使用 这是http.post 而不是
http.post实例化一个没有构造函数的类听起来像是胡说八道。嗨,Asim,问题是UploadAdapter不是一个组件,而是另一个处理与api通信的服务本身。我不能将ApiService注入UploadAdapter的构造函数中,否则在实例化它时,我需要使用以下内容:new UploadAdapternew ApiServicenew HttpClient,new Globals