Angular 未在组件中注入角度服务-错误:StaticInjectorError(AppModule)
我试图将服务Angular 未在组件中注入角度服务-错误:StaticInjectorError(AppModule),angular,typescript,Angular,Typescript,我试图将服务SpotifyService注入组件SearchComponent,该服务将Http作为参数 这是我的模块: @NgModule({ imports: [ BrowserModule, FormsModule, RouterModule ], declarations: [ AppComponent, SearchComponent, ArtistComponent, AlbumComponent, TrackComponent ], bootstrap:
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小提琴:
为什么要向工厂申报呢?只需像
提供者:[SpotifyService]
那样提供它,DI就会为您注入所有依赖项。
为此,还应正确导入HttpModule
和RouterModule
imports: [ BrowserModule, FormsModule, RouterModule.forRoot([]), HttpModule ]
并设置一些有效的路由
imports: [ BrowserModule, FormsModule, RouterModule.forRoot([]), HttpModule ]