简体   繁体   中英

Angular Material md-icon error No provider for Http

When using <md-icon> I get this error:

ORIGINAL EXCEPTION: No provider for Http!

So I added HTTP_PROVIDERS to my component and it solved it. So my question... Why do I need to add HTTP_PROVIDERS to my component to get <md-icon> to work even though I'm not using HTTP_PROVIDERS in my app otherwise?!

Here's my working component. Removing HTTP_PROVIDERS from the providers array throws the above error.

import { Component } from '@angular/core';
import { HTTP_PROVIDERS } from '@angular/http';
import { MdIcon, MdIconRegistry } from '@angular2-material/icon';

@Component({
  moduleId: module.id,
  selector: 'foo-app',
  template: `<md-icon>face</md-icon>`,
  directives: [ MdIcon ],
  providers: [MdIconRegistry, HTTP_PROVIDERS]
})
export class FooAppComponent {
  title = 'Material 2 Foo App';
}

One other note, this line will display the icon with no Http error and no need for HTTP_PROVIDERS :

<i class="material-icons">face</i>

Looking into the source code a bit for angular2-material, md-icon depends on angular2's Http which is why you're seeing the need for HTTP_PROVIDERS.

heres a link to the source: https://github.com/angular/material2/blob/master/src/components/icon/icon.ts

in /src/components/icon/icon.ts, the class requires MdIconRegistry with MdIcon having the constructor:

constructor(
  private _element: ElementRef,
  private _renderer: Renderer,
  private _mdIconRegistry: MdIconRegistry) { }

and MdIconRegistry requires Http with MdIconRegistry having the constructor:

  constructor(private _http: Http) {}

I guess Http is used to perhaps get icons from a url? So if you dig a few levels down into the source code, you can find Http in there.

Angular 7

For me the solution to this error was to add MatIconRegistry to providers on my APP module:

@NgModule({
  declarations: [..],
  imports: [
   ..,MatIconModule,
    HttpClientModule,
   ..
  ],
  providers:[  MatIconRegistry ],
  exports: [..]
})
export class SomeModule { }

Looking at the source reveals that MdIcon uses MdIconRegistry which uses Http to load the icon. This is also mentioned in a comment for MdIcon.

It still seems strange that that library is not self contained, but for now that seems to be the way it is.

Using angular 2.1.0 and angular material 2.0.0-alpha.10 do the following:

import { MaterialModule } from '@angular/material';

@NgModule({
  imports: [
    MaterialModule.forRoot(),
  ]
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM