【问题标题】:Angular Service not getting injected in component - Error: StaticInjectorError(AppModule)Angular Service 未注入组件 - 错误:StaticInjectorError(AppModule)
【发布时间】:2018-09-07 15:25:49
【问题描述】:

我正在尝试将服务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)

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

【问题讨论】:

    标签: angular typescript


    【解决方案1】:
      providers: [{
        provide:SpotifyService,
        deps: [Http], useFactory(http:Http){
            return new SpotifyService(http);
        }}]
    

    为什么要用工厂声明它?
    只需像 providers: [SpotifyService] 一样提供它,然后 DI 会为您注入所有依赖项。 为此,您还应该正确导入HttpModuleRouterModule

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

    并设置一些有效的路线。

    【讨论】:

      猜你喜欢
      • 2020-05-19
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 1970-01-01
      • 2023-03-31
      相关资源
      最近更新 更多