首页 > 解决方案 > 如何在不使用构造函数的情况下实例化 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.
         });
    }



}

标签: angulartypescript

解决方案


您没有在组件中注入服务

你的UploadAdapter构造函数应该是这样的

constructor(private http: ApiService) {}

你还需要使用

this.http.post

代替

http.post


推荐阅读