2016-08-12 4 views
1

Я только что обновил с ng2 rc4 с material2 alpha6 до ng2 rc5 с material 2 alpha7-2. Новая ошибка появляется в коде, который работал до того, как я использовал <md-icon>.Угловой 2 Материал. Тот же MdIcon, который работает в одном компоненте, не работает в другом

Я не могу увидеть полный текст сообщения об ошибке, потому что вместо того, чтобы я получаю Observable_1.Observable.throw is not a function ошибку (сбой приложения), с верхними строчками в StackTrace существах:

MdIconRegistry.prototype.getNamedSvgIcon 
    @angular2-material/icon/icon-registry.js:180:16 
MdIcon.prototype.ngOnChanges 
    @angular2-material/icon/icon.js:107:17 

Если я console.log() идентификатор значка искал чуть выше icon-registry.js @ line 180, я вижу ic_lightbulb_outline_24px. Этот значок присутствует в моем svg спрайте, но он отображается правильно, прежде чем я обновил сегодня до material 2 alpha 7-2. Вот его раздел в формате SVG спрайт:

...<svg viewBox="..." id="ic_lightbulb_outline_24px"><path d="..."/></svg>... 

Шаблон:

<md-icon svgIcon="ic_lightbulb_outline_24px"></md-icon> 

В моей главной AppComponent меня

this._iconRegistry.addSvgIconSet('src/icons/sprite.defs.svg'); 

Я также импортирован MdIconModule в основной AppModule. Что действительно вызывает недоумение то, что

  • тот же значок из того же файла спрайтов работает на других компонентах и ​​
  • это работало перед обновлением!

еще два куска информации:

  • эта проблема затрагивает только ленивые загружены модули
  • Тот же шаблон компонент с <md-icon> будет работать хорошо, если он используется в шаблоне компоненты, загруженном в приложении запускается, но с ошибкой будет ошибкой, если он используется на шаблоне компонента, который был ленив.

I've built a PlunkrI've built a Plunkr, демонстрирующий проблему. Вы заметите, что загруженные компоненты (AppComponent и HomeComponent) могут отображать значок. Однако LazyLoadedComponent не может.

Ниже приводится полный StackTrace:

MdIconRegistry.prototype.getNamedSvgIcon /@angular2-material/icon/icon-registry.js:180:16 
MdIcon.prototype.ngOnChanges /@angular2-material/icon/icon.js:107:17 
anonymous/[email protected]ProfileComponent.ngfactory.js:1318:29 
AppView</AppView.prototype.detectChanges /@angular/core//bundles/core.umd.js:12586:13 
AppView</AppView.prototype.detectContentChildrenChanges /@angular/core//bundles/core.umd.js:12604:17 
anonymous/[email protected]ProfileComponent.ngfactory.js:294:3 
AppView</AppView.prototype.detectChanges /@angular/core//bundles/core.umd.js:12586:13 
AppView</AppView.prototype.detectContentChildrenChanges /@angular/core//bundles/core.umd.js:12604:17 
anonymous/[email protected]ProfileComponent.ngfactory.js:37:3 
AppView</AppView.prototype.detectChanges /@angular/core//bundles/core.umd.js:12586:13 
AppView</AppView.prototype.detectViewChildrenChanges /@angular/core//bundles/core.umd.js:12612:17 
anonymous/_[email protected]UserProfileComponent.ngfactory.js:28:3 
AppView</AppView.prototype.detectChanges /@angular/core//bundles/core.umd.js:12586:13 
AppView</AppView.prototype.detectContentChildrenChanges /@angular/core//bundles/core.umd.js:12604:17 
AppView</AppView.prototype.detectChangesInternal /@angular/core//bundles/core.umd.js:12596:13 
AppView</AppView.prototype.detectChanges /@angular/core//bundles/core.umd.js:12586:13 
AppView</AppView.prototype.detectViewChildrenChanges /@angular/core//bundles/core.umd.js:12612:17 
AppView</AppView.prototype.detectChangesInternal /@angular/core//bundles/core.umd.js:12597:13 
AppView</AppView.prototype.detectChanges /@angular/core//bundles/core.umd.js:12586:13 
AppView</AppView.prototype.detectContentChildrenChanges /@angular/core//bundles/core.umd.js:12604:17 
anonymous/[email protected].ngfactory.js:445:3 
AppView</AppView.prototype.detectChanges /@angular/core//bundles/core.umd.js:12586:13 
AppView</AppView.prototype.detectViewChildrenChanges /@angular/core//bundles/core.umd.js:12612:17 
anonymous/[email protected]onent.ngfactory.js:30:3 
AppView</AppView.prototype.detectChanges /@angular/core//bundles/core.umd.js:12586:13 
ViewRef_</ViewRef_.prototype.detectChanges /@angular/core//bundles/core.umd.js:10804:58 
ApplicationRef_</ApplicationRef_.prototype.tick/< /@angular/core//bundles/core.umd.js:10191:79 
ApplicationRef_</ApplicationRef_.prototype.tick /@angular/core//bundles/core.umd.js:10191:17 
ApplicationRef_/<.next/< /@angular/core//bundles/core.umd.js:10095:103 
Zone</ZoneDelegate</ZoneDelegate.prototype.invoke /zone.js/dist/zone.js:323:20 
NgZoneImpl/this.inner<.onInvoke /@angular/core//bundles/core.umd.js:9245:36 
Zone</ZoneDelegate</ZoneDelegate.prototype.invoke /zone.js/dist/zone.js:322:20 
Zone</Zone</Zone.prototype.run /zone.js/dist/zone.js:216:25 
NgZoneImpl</NgZoneImpl.prototype.runInner /@angular/core//bundles/core.umd.js:9276:64 
NgZone</NgZone.prototype.run /@angular/core//bundles/core.umd.js:9505:55 
ApplicationRef_/<.next /@angular/core//bundles/core.umd.js:10095:73 
EventEmitter</EventEmitter.prototype.subscribe/schedulerFn< /@angular/core//bundles/core.umd.js:9168:58 
SafeSubscriber.prototype.__tryOrUnsub /rxjs/Subscriber.js:225:13 
SafeSubscriber.prototype.next /rxjs/Subscriber.js:174:17 
Subscriber.prototype._next /rxjs/Subscriber.js:124:9 
Subscriber.prototype.next /rxjs/Subscriber.js:88:13 
Subject.prototype._finalNext /rxjs/Subject.js:128:13 
Subject.prototype._next /rxjs/Subject.js:120:13 
Subject.prototype.next /rxjs/Subject.js:77:9 
EventEmitter</EventEmitter.prototype.emit /@angular/core//bundles/core.umd.js:9156:58 
NgZone</NgZone.prototype._checkStable /@angular/core//bundles/core.umd.js:9415:25 
NgZone/this._zoneImpl<.onLeave /@angular/core//bundles/core.umd.js:9387:21 
NgZoneImpl/this.inner<.onInvokeTask /@angular/core//bundles/core.umd.js:9239:29 
Zone</ZoneDelegate</ZoneDelegate.prototype.invokeTask /zone.js/dist/zone.js:355:24 
Zone</Zone</Zone.prototype.runTask /zone.js/dist/zone.js:256:29 
ZoneTask/this.invoke /zone.js/dist/zone.js:423:29 

Любые идеи?

(перекрестная отправил on github)

ответ

1

(это воспроизводство my post here, поскольку эти два вопроса действительно то же самое)

я понял, что из-за MdIconModule сам имеет MdIconRegistry службу в providers массив, каждый другой модуль импортирует его, предоставляется новый экземпляр службы. В результате все компоненты, загруженные во время начальной загрузки и принадлежащие одному и тому же AppModule, используют один и тот же экземпляр этой службы.Однако компоненты, загруженные позже (через lazy-load), имеют другой экземпляр службы и, как результат, не могут видеть значки, зарегистрированные во время загрузки.

С help from James, я использовал обходной путь из специально созданного модуля, который не использует MdIconModule вообще, а скорее объявляет MdIcon класс в одиночку. Затем я предоставляю услугу MdIconRegistry отдельно и только к корню AppComponent. В результате всего лишь один экземпляр приложения-приложения и значки, зарегистрированные во время загрузки, доступны повсюду.

Модифицированный MdIconFixedModule

@NgModule({ 
    imports: [CommonModule, HttpModule], 
    declarations: [MdIcon], 
    exports: [MdIcon], 
    providers: [],//leave empty to avoid multiple instances of MdIconRegistry 
}) 
export class MdIconFixedModule { 
    static forRoot() { 
     return { 
      ngModule: MdIconFixedModule, 
      //will be available only to whoever calls .forRoot() 
      providers: [MdIconRegistry] 
     }; 
    } 
} 

модули, которые необходимо использовать только иконки можно импортировать MdIconFixedModule как это не содержит MdIconRegistry. AppModule, который также должен регистрировать значки импорта MdIconFixedModule.forRoot(), который действительно содержит эту услугу.

Детали этой реализации can be seen here.

Это ограничение модулей нг-материала является щелевой быть fixed with the alpha 8 release.

Смежные вопросы