Http-функция получения не принимает параметры - PullRequest
0 голосов
/ 28 января 2020

Я пытаюсь загрузить файл с помощью filesaver в Angular. Хотя я могу добавлять параметры в свою функцию получения HttpCient, в тот момент, когда я переключаюсь на пользовательский http-модуль, который я написал, чтобы я мог включить заголовки авторизации, он просто игнорирует параметры, которые я пытаюсь добавить. Я попытался изменить свою функцию получения на основе функции получения HttpClient, но, похоже, ничего не работает. К вашему сведению, модуль http работает хорошо для всех других моих служб. Любые идеи?

мой пользовательский модуль http:


  get<T>(url:string, options) {
    const httpOptions  = {
      headers: new HttpHeaders({
        'Authorization': sgwtConnect.getAuthorizationHeader(),
        'Accept': 'application/json'
      }),
      params: options
    }
    return this.http.get(url, httpOptions).toPromise();
  }


мой файловый сервис загрузки

import { Injectable } from '@angular/core';
// import {HttpWithHeadersModule} from "./httpWithHeaders/http-with-headers.module";
import {AppConfig} from "../app.config";
import {ReportBatches} from "../models/reportBatches";
import {HttpParams, HttpClient} from "@angular/common/http";
import {HttpWithHeadersModule} from "./httpWithHeaders/http-with-headers.module";

@Injectable({
  providedIn: 'root'
})
export class DownloadFileService {
  private apiUrl = '';
  private downloadFilesEndPoint;
  // private pathToDownload = String;

  constructor(private http: HttpWithHeadersModule, private appConfig: AppConfig) {
    this.apiUrl = this.appConfig.settings.apiServer.apiUrl;
    this.downloadFilesEndPoint = this.appConfig.settings.apiServer.downloadFileEndPoint;
  }

downloadFile(data) {
    const REQUEST_PARAMS = new HttpParams().set('pathToDownload', data.pathToDownload);
    const REQUEST_URI = this.downloadFilesEndPoint;
    return this.http.get(REQUEST_URI,
             REQUEST_PARAMS
            //responseType: 'arraybuffer'
    )
  }
}

мой компонент TS enet

import {animate, state, style, transition, trigger} from '@angular/animations';
import {Component, OnInit, ViewChild} from '@angular/core';
import {MatPaginator} from "@angular/material/paginator";
import {MatSort} from "@angular/material/sort";
import {from} from 'rxjs';
import {ReportService} from 'src/app/services/report.service';
import {DownloadFileService} from "../../../services/download-file.service";
import {DatePipe} from '@angular/common';
import {ReportBatches} from "../../../models/reportBatches";
import {MatTableDataSource} from "@angular/material/table";
import {saveAs} from 'file-saver';

@Component({
  selector: 'app-report',
  styleUrls: ['./report.component.scss'],
  templateUrl: './report.component.html',
  animations: [
    trigger('detailExpand', [
      state('void', style({height: '0px', minHeight: '0', visibility: 'hidden'})),
      state('*', style({height: '*', visibility: 'visible'})),
      transition('void <=> *', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)'))
    ])
  ],
})
export class ReportComponent implements OnInit {
  reportBatches: ReportBatches[];
  dateValue = new Date();
  maxDate = new Date();
  currentDate = new Date();
  dataSource: MatTableDataSource<ReportBatches>;
  expandedElement: ReportBatches | null;

  displayedReportsColumn: string[] = ['transferStatus', 'fisReportName', 'lastModified', 'numberOfRecords', 'addArrow'];

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  isExpansionDetailRow = (index, row) => row.hasOwnProperty('detailRow');

  constructor(private reportService: ReportService, private downloadFileService: DownloadFileService, private datePipe: DatePipe) {
  }

  ngOnInit() {
    this.callReportService(new Date());
  }

  reportDateChange(value: Date) {

    const currentValue = this.datePipe.transform(this.dateValue, 'yyyyMMdd');
    const newSelectedValue = this.datePipe.transform(value, 'yyyyMMdd');
    if (currentValue !== newSelectedValue) {
      this.callReportService(value);
      this.dateValue = value;
    }
  }

  callReportService(value: Date) {
    from(this.reportService.getReportsAndBatches(value))
      .subscribe(res => {
        this.reportBatches = <ReportBatches[]>res;
        // console.log(JSON.stringify(this.reportBatches));
        this.dataSource = new MatTableDataSource(this.reportBatches);
        // this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
      });
  }

  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
    this.dataSource.filter = filterValue;
  }

  refreshDate() {
    this.callReportService(this.dateValue);
  }

  downloadFile(pathToDownload) {
    console.log(pathToDownload);
    from(this.downloadFileService.downloadFile({'pathToDownload': pathToDownload}))
  .subscribe((data:any)  => {
    saveAs(new Blob([data], {type: 'application/octet-stream'}), pathToDownload);
    })
  }


}

мой html файл

<div class="container-fluid">
  <form>
      <label for="reportDate" class="col-form-label">Enter Creation Date:</label>
      <div class="input1">
        <input id="reportDate"
               class="form-control"
               #dp="bsDatepicker"
               (bsValueChange)="reportDateChange($event)"
               [maxDate]="maxDate"
               bsDatepicker
               [bsValue]="dateValue"
               [bsConfig]="{ isAnimated: true, adaptivePosition: true, dateInputFormat: 'YYYY-MM-DD', containerClass: 'theme-red'}"/>
      </div>
      <div class="input1">
        <mat-form-field color="warn" appearance="legacy">
          <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
        </mat-form-field>
      </div>
      <!--    <div class="input1">Last Refreshed at: {{currentDate | date :'mediumTime'}}</div>-->
      <div class="input1">
        <button class="btn btn-danger btn-lg" (click)="refreshDate()">
          <span class="glyphicon glyphicon-refresh"></span>Refresh
        </button>
      </div>
</form>
<div class="report-container mat-elevation-z8">
  <mat-table #table [dataSource]="dataSource" matSort>
    <ng-container matColumnDef="transferStatus">
      <mat-header-cell class=col1 *matHeaderCellDef mat-sort-header>Transfer Status</mat-header-cell>
      <mat-cell class=col1 *matCellDef="let report">{{report.transferStatus}}</mat-cell>
    </ng-container>
    <ng-container matColumnDef="fisReportName">
      <mat-header-cell class=col2 *matHeaderCellDef mat-sort-header>FIS Report Name</mat-header-cell>
      <mat-cell class=col2 *matCellDef="let report">{{report.remoteFileNameOnFTA}}</mat-cell>
    </ng-container>
    <ng-container matColumnDef="lastModified">
      <mat-header-cell class=col3 *matHeaderCellDef mat-sort-header>Last Modified</mat-header-cell>
      <mat-cell class=col3 *matCellDef="let report">{{report.lastModified | date :'medium'}}</mat-cell>
    </ng-container>
    <ng-container matColumnDef="numberOfRecords">
      <mat-header-cell class=col4 *matHeaderCellDef mat-sort-header>Number Of Records</mat-header-cell>
      <mat-cell class=col4 *matCellDef="let report">{{report.numberOfRecords}}</mat-cell>
    </ng-container>
    <ng-container class=col5 matColumnDef="addArrow">
      <mat-header-cell *matHeaderCellDef></mat-header-cell>
      <mat-cell *matCellDef="let report">
        <mat-icon (click)="expandedElement = expandedElement === report ? null : report">expand_more</mat-icon>
      </mat-cell>
    </ng-container>
    <ng-template #tpl let-report>
      <div class="mat-row detail-row" [@detailExpand] style="overflow: hidden">
        <mat-list>
          <mat-list-item><b class="title">File Size: </b>{{report.contentLength}}</mat-list-item>
          <mat-list-item><b class="title">Creation Date:</b> {{report.creationDate | date}}</mat-list-item>
          <mat-list-item><b class="title">Azure File Name:</b> {{report.adlsFullPath}}</mat-list-item>
          <!--          .substring(report.adlsFullPath.indexOf('part'))}}-->
          <mat-list-item><b class="title">Data Path:</b> {{report.dataPath}}</mat-list-item>
          <mat-list-item><b class="title">Batch Version:</b> {{report.version}}</mat-list-item>
          <mat-list-item><b class="title">Batch Source:</b> {{report.source}}</mat-list-item>
                    <mat-list-item><b class="title"><button class="btn btn-danger btn-lg" (click)="downloadFile(report.adlsFullPath)">Download File</button></b></mat-list-item>
        </mat-list>
      </div>
    </ng-template>
    <mat-header-row *matHeaderRowDef="displayedReportsColumn"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedReportsColumn;" matRipple
             class="element-row" [cdkDetailRow]="row"
             [cdkDetailRowTpl]="tpl">
    </mat-row>
  </mat-table>
</div>
</div>

1 Ответ

0 голосов
/ 30 января 2020

моя ошибка заключалась в том, что я забыл добавить api_url, поэтому получатель вызывал localhost вместо моего api. Это исправленный код для функции загрузки в моем сервисе загрузки:

downloadFile(data) {
    const REQUEST_PARAMS = new HttpParams().set('pathToDownload', data.pathToDownload);
    const REQUEST_URI = this.apiUrl + this.downloadFilesEndPoint;
    // console.log('uri is: ', REQUEST_URI);
    return this.http.get(REQUEST_URI, {
      params: REQUEST_PARAMS,
      responseType: 'arraybuffer'
    })
  }

...