如何在不使用构造函数的情况下实例化Angular 2服务




我正在尝试在另一个类中使用我的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});
  }
  ...
}

class呼叫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

相关内容

最新更新