角服务未注入组件中-错误:StaticInjectorError(AppModule)

时间:2018-09-07 07:09:11

标签: angular typescript

我试图将服务SpotifyService注入组件SearchComponent,该服务将Http作为参数。

这是我的模块:

@NgModule({
  imports:      [ BrowserModule, FormsModule, RouterModule ],
  declarations: [ AppComponent, SearchComponent, ArtistComponent, AlbumComponent, TrackComponent ],
  bootstrap:    [ AppComponent ],
  providers: [{
    provide:SpotifyService,
    deps: [Http], useFactory(http:Http){
        return new SpotifyService(http);
    }}]
})
export class AppModule { }

和服务:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { from, Observable, throwError } from 'rxjs';
import { map, filter, catchError, mergeMap } from 'rxjs/operators';

@Injectable()
export class SpotifyService {

  constructor(public http: Http) { }

  searchTrack(query:string){
    let params:string = [
      `q=${query}`,
      `type=track`
    ].join("&");

    let queryUrl:string = `https://api.spotify.com/v1/search?${params}`;

    return this.http.request(queryUrl).
pipe(map((e)=> e.json()),
      catchError((e:Response)=> throwError(e)));
  }

}

搜索组件定义:

export class SearchComponent implements OnInit {
  query:string;
  results: Object;
  constructor(private spotify: SpotifyService,
  private router: Router,
  private route: ActivatedRoute) { 
    this.route.queryParams.subscribe(params=>{
      this.query = params["query"] || "";
    });
  }
}//etc...

但是在运行时我得到了黑屏,显示错误Error: StaticInjectorError(AppModule)

这里是堆闪电小提琴:https://stackblitz.com/edit/angular-spotify-ngbook

1 个答案:

答案 0 :(得分:1)

  providers: [{
    provide:SpotifyService,
    deps: [Http], useFactory(http:Http){
        return new SpotifyService(http);
    }}]

为什么要在工厂申报呢?
只需提供providers: [SpotifyService]之类的内容,然后DI为您注入所有依赖项。 为此,您还应该正确导入HttpModuleRouterModule

imports:      [ BrowserModule, FormsModule, RouterModule.forRoot([]), HttpModule ]

并设置一些有效的路线。