Angular2 Typescript静态构造函数声明

Angular2 Typescript static constructor declaration

我缺乏对静态 classes 的一些练习,因此,我无法正确初始化。我有以下 class:

import { HttpEvent, HttpClient, HttpRequest, HttpEventType } from '@angular/common/http';

export class Utils {

  static http: any;
  constructor(private http: HttpClient) {}

  static uploadMediaFile(file, api: string, model: any) {
    const formData = new FormData();
    formData.append(file.name, file);
    const uploadReq = new HttpRequest("POST", api, formData, {
      reportProgress: true,
    });

    this.http.request(uploadReq).subscribe(event => {
     //blah blah
    });  
  }
}

上面的执行,returns:"ERROR TypeError: Cannot read property 'request' of undefined"

尝试调试,http 似乎未定义(console.log),所以我认为初始化不正确。

欢迎任何帮助

我看到您想使用 formData 对象执行 POST 请求。您可以使用 http.post 而不是 request 方法

并且不需要使用 static http: any。此外,您的方法不必是 static.

export class Utils {

  constructor(private http: HttpClient) {}

  uploadMediaFile(file, api: string, model: any) {
    const formData = new FormData();
    formData.append(file.name, file);
    const uploadReq = new HttpRequest("POST", api, formData, {
      reportProgress: true,
    });

    this.http.post(uploadReq).subscribe(event => {
     //blah blah
    });  
  }
}

如果您创建 Utils class 的新实例,class constructor 将调用,而另一侧 static (http) 刚刚声明没有分配一个值,为什么 Utils.http 是未定义的。 我相信你可能会混淆 angular 依赖注入,最好的情况是创建 UtilsService 一个注入的 http 对象而不是使用静态方法。

@Injectable()
export class UtilsService {

  constructor(private http: HttpClient) {}

  uploadMediaFile(file, api: string, model: any) {
    const formData = new FormData();
    formData.append(file.name, file);
    const uploadReq = new HttpRequest("POST", api, formData, {
      reportProgress: true,
    });

    this.http.request(uploadReq).subscribe(event => {
     //blah blah
    });  
  }
}

如果你想使用 Utils 的静态方法,你必须在使用它之前手动分配一个 http 对象

Utils.http = http; 

之后就可以使用了;