0

我正在尝试在 Promise 函数中发出 http 请求。我明白了this.http.postundefined error... 我知道我必须以this某种其他方式访问,但我不明白该怎么做。

有人愿意帮助我吗?

doUpload(files: Array<File>): Promise<Array<UploadResult>> {
    console.log(files);
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        let result: Array<UploadResult> = [];
        for (let file of files) {
          this.http
            .post(this.APIURL + "/image/upload/markdown", file)
            .subscribe((data) => {
              console.log(data);
            });
          result.push({
            name: file.name,
            url: `https://avatars3.githubusercontent.com/${file.name}`,
            isImg: file.type.indexOf("image") !== -1,
          });
        }
        resolve(result);
      }, 3000);
    });
  }

错误:

> TypeError: undefined is not an object (evaluating 'this.http.post')  
> (anonyme Funktion) — sensor-edit.component.ts:308  
> onInvokeTask — core.js:39680  
> runTask — zone-evergreen.js:168  
> invokeTask — zone-evergreen.js:465  
> timer — zone-evergreen.js:2650

构造函数:

constructor(
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private api: ApiService,
    private _routerService: Router,
    private errorService: ErrorModalService,
    private sanitizer: DomSanitizer,
    private http: HttpClient
  ) {}

doUpload在我的 Html 中这样调用:

<div class="container well come-space">
          <md-editor formControlName="markdown" name="Content" [height]="'400px'" [upload]="doUpload">
          </md-editor>
</div>
4

1 回答 1

0

TBH,我在这里看不到将 Observable 转换为 Promise 的用途。事实上,目前您正在创建多个可以保持打开状态的订阅。相反,我会使用 RxJSforkJoin在单个订阅中并行触发多个可观察对象。

尝试以下

import { forkJoin, Observable } from 'rxjs';
import { map } from 'rxjs/operators';

doUpload(files: Array<File>): Observable<Array<UploadResult>> {
  return forkJoin(                                  // <-- RxJS `forkJoin` function
    files.map((file: any) =>                        // <-- `Array#map` function
      this.http.post(
        this.APIURL + "/image/upload/markdown", 
        file
      ).pipe(
        map((data: any) => ({                       // <-- RxJS `map` operator
          name: file.name,
          url: `https://avatars3.githubusercontent.com/${file.name}`,
          isImg: file.type.indexOf("image") !== -1,
        }))
      )
    )
  );
}

然后你可以订阅它

this.doUpload(files).subscribe({
  next: (response) => console.log(response),
  error: (error) => console.log(error)
});

更新

正如评论中所说,我的解决方案不能与<md-editor>'s@Input() upload变量结合使用。将您自己的doUpload()实现与组件的构造函数的以下片段一起使用。

constructor() {
  this.doUpload = this.doUpload.bind(this);
}

取自ngx-markdown-editor的文档

于 2021-10-28T12:36:38.923 回答