【发布时间】:2019-04-01 17:47:37
【问题描述】:
我正在尝试使用 Angular Material 7.2 和 Angular 7.2.11 实现具有自定义 SVG 图标的按钮。使用标准 Material 图标字体我没有遇到任何问题。然而,自定义图标只会导致控制台上出现“检索图标时出错:<svg> 未找到标签”。
我一直在挖掘 @angular/material/esm2015/icon.js 中的代码,发现 _fetchUrl() 似乎正在接收 SVG,但 HttpResponse 对象的主体是空的,尽管 ACTUAL 响应包含经 Firefox 验证的 SVG。 HttpResponse 对象中的标头包含正确的内容长度。
将 HttpResponse 对象报告的 URL 粘贴到浏览器中会呈现正确的 SVG。
_fetchUrl() 正在使用 HttpClient::get() 的 'text' responseType 选项,据我所知,这应该没问题,尽管响应指定了content-type: image/svg+xml。可以肯定的是,我重命名了 SVG 并给它一个 'txt' 扩展名。随后的响应具有 text/plain 内容类型,但 HttpResponse 的主体仍然是空的。
从等式中删除材料图标注册表并尝试简单的get() 会产生相同的问题。请求成功完成,SVG 已发送,但 HttpResponse 的正文为空。
应用模块:
import { HttpClientModule, ... } from '@angular/common/http';
import {
...
MatIconModule,
...
} from '@angular/material';
@NgModule({
...
imports: [
...
HttpClientModule,
MatIconModule
...
],
...
})
应用组件:
@Component({
...
})
export class AppComponent {
constructor(private router: Router, private matIconRegistry: MatIconRegistry, private domSanitizer: DomSanitizer, private http: HttpClient, ...)
{
this.matIconRegistry.addSvgIcon('test_icon',
this.domSanitizer.bypassSecurityTrustResourceUrl('/assets/svg/test.svg'));
http.get('/assets/svg/test.svg', { responseType: 'text' }) .subscribe(svg => console.log(`Response: ${svg}`));
}
}
组件 HTML:
<button mat-icon-button>
<mat-icon svgIcon="test_icon"></mat-icon>
</button>
测试 SVG 文件:
<?xml version="1.0" encoding="UTF-8" ?>
<svg width="64" height="64" version="1.1" xmlns="http://www.w3.org/2000/svg">
<rect x="0" y="0" width="64" height="64" style="fill:rgb(0,0,0,0)" />
</svg>
<svg>Test</svg>
控制台输出:
Request to access cookie or storage on “https://fonts.googleapis.com/icon?family=Material+Icons” was blocked because we are blocking all third-party storage access requests and content blocking is enabled. calendar
Angular is running in the development mode. Call enableProdMode() to enable the production mode. core.js:21273
Error retrieving icon: <svg> tag not found icon.js:867:81
请求/响应:
GET /assets/svg/test.svg HTTP/1.1
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: *
Accept-Ranges: bytes
Content-Type: image/svg+xml; charset=UTF-8
Content-Length: 219
ETag: W/"d9-8SqOE9sCdf/cpMgr8wAdHVFXV+g"
Date: Tue, 02 Apr 2019 00:36:12 GMT
Connection: keep-alive
<?xml version="1.0" encoding="utf-8" ?>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
<rect x="0" y="0" width="32" height="32" style="fill:rgb(0,0,0,0)" />
</svg>
【问题讨论】:
标签: angular svg angular-material angular-httpclient