您好,我的项目中有一个 components/home-component/home.component.html
和 components/home-component/home.component.ts
。我还有一个 svg
文件 assets/homenav/home_icon.svg
。我正在 home.component.ts
的构造函数中加载图标:
import { Component, OnInit } from '@angular/core';
import { MdIconRegistry } from '@angular/material';
import { DomSanitizer } from '@angular/platform-browser';
@Component({
moduleId: module.id,
templateUrl: 'home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private iconRegistry: MdIconRegistry, private sanitizer: DomSanitizer) {
iconRegistry.addSvgIcon('home', sanitizer.bypassSecurityTrustResourceUrl('assets/homenav/home_icon.svg'));
}
ngOnInit() { }
}
如果我运行我的应用程序,应用程序本身可以正常工作。虽然图标没有被渲染。我正在加载这样的图标:
<md-icon class="homeNavIcon" color="primary" svgIcon="home"></md-icon>
没有错误消息或任何其他提示。如果我输入 http://localhost:4200/assets/homenav/home_icon.svg
作为 url,图标会正确显示在浏览器中。
此外,如果我在 HomeComponent
构造函数中设置断点并尝试在控制台中调用 iconRegistry
call,我会得到:
我还尝试将 url 更改为:
iconRegistry.addSvgIcon('home', sanitizer.bypassSecurityTrustResourceUrl('/../../../assets/homenav/home_icon.svg'));
和其他几个没有运气的组合。如果我将 home.component
直接放入 app
文件夹,它也似乎可以工作。
我是否提供了错误的 url 或我是否遗漏了其他内容。
更新:
我意识到如果图标在我的其他项目中正确显示,svgElement
也是空的。我还想概述一下我的 @NgModule
:
@NgModule({
declarations: [
AppComponent,
LoginComponent,
HomeComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
MaterialModule,
MdCardModule,
HttpModule,
BrowserAnimationsModule
],
providers: [
AuthGuard,
AuthenticationService,
UserService,
// providers used to create fake backend
fakeBackendProvider,
MockBackend,
BaseRequestOptions
],
bootstrap: [AppComponent]
})
export class AppModule { }
更新 2:
正如我已经假设的那样,MdIconRegistry
中的图标从未加载过。我可以插入任何废话作为 Url,这不会引发任何错误。即:
iconRegistry.addSvgIcon('home',
sanitizer.bypassSecurityTrustResourceUrl('LoremIpsumblabla'));
这个调用不会抛出任何异常,而在另一个项目中我得到:
Failed to load resource: the server responded with a status of 404 (Not Found) :4200/LoremIpsumblabla
最佳答案
尝试改变这个路径
'./assets/homenav/home_icon.svg'
关于angular - 通过 MdIconRegistry 和 DomSanitizer 从 Assets 中检索图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45905807/