Sup*_*miu 16 javascript angular2-http angular
对于Web应用程序,我需要使用ajax请求获取我的图像,因为我们的API上有签名+身份验证,因此我们无法使用简单的方法获取图像 <img src="myapi/example/145"/>
由于我们使用的是angular2,我们显然会查找blob或类似的东西,但正如static_response.d.ts文件中所述:
/**
* Not yet implemented
*/
blob(): any;
Run Code Online (Sandbox Code Playgroud)
好吧,我现在不能这样做,我必须等待你的功能实现.
但问题是我迫不及待所以我需要一个修补程序或一点点黑客才能从响应中获取图像数据,我将能够删除我的hack并将blob()方法调用设置为良好的时候实现它.
我试过这个:
export class AppComponent {
constructor(private api:ApiService, private logger:Logger){}
title = 'Tests api';
src='http://placekitten.com/500/200'; //this is src attribute of my test image
onClick(){ //Called when I click on "test" button
this.api.test().then(res => {
console.log(res._body);
var blob = new Blob([new Uint8Array(res._body)],{
type: res.headers.get("Content-Type")
});
var urlCreator = window.URL;
this.src = urlCreator.createObjectURL(blob);
});
}
}
Run Code Online (Sandbox Code Playgroud)
与ApiService.test()方法:
test():Promise<any> {
return this.http.get(this._baseUrl + "myapi/example/145", this.getOptions())
//getOptions() is just creating three custom headers for
//authentication and CSRF protection using signature
.toPromise()
.then(res => {
this.logger.debug(res);
if(res.headers.get("Content-Type").startsWith("image/")){
return res;
}
return res.json();
})
.catch(res => {
this.logger.error(res);
return res.json();
} );
}
Run Code Online (Sandbox Code Playgroud)
但我没有从中获取任何图像,并且记录响应数据显示了一个大字符串,即图像数据.
你有没有实现这个目标?
tsc*_*ege 27
没有必要再延长BrowserXhr.(使用angular 2.2.1测试)
RequestOptionsArgs现在有一个responseType: ResponseContentType可以设置的属性ResponseContentType.Blob
使用DomSanitizer
import {DomSanitizer} from '@angular/platform-browser';
Run Code Online (Sandbox Code Playgroud)
此示例还创建了一个可以绑定到的src属性的已清理URL<img>
this.http.get(url, {
headers: {'Content-Type': 'image/jpg'},
responseType: ResponseContentType.Blob
})
.map(res => {
return new Blob([res._body], {
type: res.headers.get("Content-Type")
});
})
.map(blob => {
var urlCreator = window.URL;
return this.sanitizer.bypassSecurityTrustUrl(urlCreator.createObjectURL(blob));
})
Run Code Online (Sandbox Code Playgroud)
Cuz*_*zox 10
使用新的Angular HttpClient非常容易实现.离开tschuege的方法,它将是:
return this._http.get('/api/images/' + _id, {responseType: 'blob'}).map(blob => {
var urlCreator = window.URL;
return this._sanitizer.bypassSecurityTrustUrl(urlCreator.createObjectURL(blob));
})
Run Code Online (Sandbox Code Playgroud)
关键是将responseType设置为'blob',以便它不会尝试将其解析为JSON
| 归档时间: |
|
| 查看次数: |
28898 次 |
| 最近记录: |