属性"map"在类型"可观察"上不存在<Blob>



我想使用Angular 6代码实现文件下载:

其余API:

@GetMapping("export")
public ResponseEntity<InputStreamResource> export() throws IOException {
ClassPathResource pdfFile = new ClassPathResource(EXTERNAL_FILE_PATH);
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
return ResponseEntity.ok().headers(headers).contentLength(pdfFile.contentLength())
.contentType(MediaType.parseMediaType("application/pdf"))
.body(new InputStreamResource(pdfFile.getInputStream()));
}

服务:

import {Injectable} from '@angular/core';
import {HttpClient, HttpParams} from "@angular/common/http";
import {Observable} from "rxjs/index";
import {environment} from "../../../environments/environment";
import {HttpUtils} from "../common/http-utils";
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class DownloadService {
constructor(private http: HttpClient) {
}
downloadPDF(): any {
return this.http.get(environment.api.urls.downloads.getPdf, { responseType: 'blob' }).map(
(res) => {
return new Blob([res.blob()], { type: 'application/pdf' });
});
}  
}

组件:

import {Component, OnInit} from '@angular/core';
import {DownloadService} from "../service/download.service";
import {ActivatedRoute, Router} from "@angular/router";
import {flatMap} from "rxjs/internal/operators";
import {of} from "rxjs/index";
import { map } from 'rxjs/operators';
@Component({
selector: 'app-download',
templateUrl: './download.component.html',
styleUrls: ['./download.component.scss']
})
export class DownloadComponent implements OnInit {
constructor(private downloadService: DownloadService,
private router: Router,
private route: ActivatedRoute) {
}
ngOnInit() {   
}
export() {               
this.downloadService.downloadPDF().subscribe(res => {
const fileURL = URL.createObjectURL(res);
window.open(fileURL, '_blank');
});         
} 
}

当我启动angular时,我得到错误:src/app/panel/service/download.service.ts(17,91(中的error:错误TS2339:类型"Observable"上不存在属性"map"。

map导入代码的正确wya是什么?当我按下下载按钮时,什么也没发生。

您可能正在使用Rxjs 5.5或更高版本。

在Rxjs 5.5之后,不能再在Observable Value上直接链接像map这样的运算符。您必须使用.pipe,然后传递逗号分隔的运算符列表。

import { map } from 'rxjs/operators';
...
downloadPDF(): any {
return this.http.get(environment.api.urls.downloads.getPdf, {
responseType: 'blob',
observe: 'response'
})
.pipe(
map((res: any) => {
return new Blob([res.blob()], { type: 'application/pdf' });
})
);
}

这是样品StackBlitz供您参考。

顺便说一句,Explorer是一个惊人的工具,可以检查Rxjs语法迄今为止的变化。

您可以这样调用请求,因为您使用的是angular 6

downloadPDF(): any {
return this.http.get(environment.api.urls.downloads.getPdf, { responseType: 'blob' });
}  

更新:导入ResponseContentType

从"@angular/Http"导入{Http,ResponseContentType};

相关内容

最新更新