![](/img/trans.png)
[英]Angular 9 - Error: StaticInjectorError[Http]: StaticInjectorError[Http]: NullInjectorError: No provider for Http
[英]Angular 2 error NullInjectorError: No provider for Http
我正在尝试读取json github服务,但出现错误NullInjectorError:没有Http的提供程序!
我已经在所有代码中添加了提供程序,但是它无法正常工作,我不知道是什么导致了错误,但是知道发生了什么,我需要一些可以帮助理解导致此错误的原因。
import { Injectable } from '@angular/core';
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule, Http, JsonpModule} from '@angular/http';
import { Observable} from 'rxjs';
import 'rxjs/add/operator/map';
@NgModule({
imports: [
BrowserModule,
HttpModule,
JsonpModule,
]
})
@Injectable({
providedIn:'root'
})
export class GithubService{
constructor(private http:Http){
}
getUser(){
const searchText ="js";
const url = "http://api.github.com/search/users?q="+searchText;
this.http.get(url).subscribe(
res=> {
const data=res.json();
console.log(data);
return data;
}
)
}
}
我得到的错误:
AppComponent.html:7 ERROR NullInjectorError: StaticInjectorError(AppModule)[GithubService -> Http]:
StaticInjectorError(Platform: core)[GithubService -> Http]:
NullInjectorError: No provider for Http!
更新:Angular v6 +
从旧版本(Angular v2-v5)开始:HttpModule现在已被弃用,您需要将其替换为HttpClientModule,否则也会收到错误消息。
在您的app.module.ts文件中更改这些
然后更新模块imports []数组HttpClientModule
@NgModule({ imports: [ BrowserModule, FormsModule, // if used HttpClientModule, ], declarations: [ AppComponent ], bootstrap: [ AppComponent ] })
请按照以下2个步骤操作,
前往app.moudle.ts
添加JavaScript导入
import { HttpModule, Http, JsonpModule} from '@angular/http';
添加@ngModule Angular导入
imports: [ BrowserModule, AppRoutingModule, HttpModule ],
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.