how to add headers to form data in angular 5

Viewed 3284

How do I add headers to form data that has a progress bar?

I get the following error:

ERROR in src/app/services/auth.service.ts(91,23): error TS2554: Expected 2-4 arguments, but got 5.

Code:

   public upload(
    files: Set<File>
  ): { [key: string]: { progress: Observable<number> } } {
    // this will be the our resulting map
    const status: { [key: string]: { progress: Observable<number> } } = {};

    files.forEach(file => {
      // create a new multipart-form for every file

      const formData: FormData = new FormData();
      formData.append('file', file, file.name);

      // formData.append('name', course, course.name);
      // formData.append('text', username, username.name);
      let headers = new Headers();
      this.loadToken();
      headers.append('Authorization', this.authToken);
      // headers.append('Content-type', undefined);


      // create a http-post request and pass the form
      // tell it to report the upload progress

      const req = new HttpRequest('POST', 'users/upload', formData,{headers: headers},{
        reportProgress: true
      });

      // create a new progress-subject for every file
      const progress = new Subject<any>();

      // send the http-request and subscribe for progress-updates

      const startTime = new Date().getTime();
      this.https.request(req).subscribe(event => {
        if (event.type === HttpEventType.UploadProgress) {
          // calculate the progress percentage

          const percentDone = Math.round((100 * event.loaded) / event.total);
          // pass the percentage into the progress-stream
          progress.next(percentDone);
        } else if (event instanceof HttpResponse) {
          // Close the progress-stream if we get an answer form the API
          // The upload is complete
          progress.complete();
        }
      });

      // Save every progress-observable in a map of all observables
      status[file.name] = {
        progress: progress.asObservable()
      };
    });

    // return the map of progress.observables
    return status;
  }
1 Answers

ERROR in src/app/services/auth.service.ts(91,23): error TS2554: Expected 2-4 arguments, but got 5.

The error message says that it expected 2-4 arguments, but got 5.

headers and reportProgress shouldn't be separate arguments, they both should be part of the fourth argument in HttpRequest.

To fix the error, change the HttpRequest as shown below:

const req = new HttpRequest('POST', 'users/upload', formData,
  { headers: headers, reportProgress: true });
Related