背景:
我在Angular项目准备加一个“CommonService”的服务来专门管控请求,但是代码写完了,HttpClient模块也注入了,可是运行起来就是死命报错,涉及到“CommonService”的组件均因为报错无法显示内容,由此开始了修bug之路。
原代码:
CommonService服务
在构造方法中引入了HttpClient,在这一页VSCode没有提示报错
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CommonService {
domain: string = "localhost:8083";
constructor(private http: HttpClient) { }
/**
* 将域名和接口名组合起来返回完整URL
* @param interfaceName 接口名,例如:“/user/login”
* @returns 拼接后完整url
*/
getUrl(interfaceName: string): string{
return this.domain+interfaceName;
}
//发送Get请求
httpGet(interfaceName: string, load: any){
var url = this.getUrl(interfaceName);
return new Promise((resove, reject) => {
this.http.get(url).subscribe(
(response) => {
resove(response);
}, (error) => {
reject(error);
}
)
});
}
}
app.module.ts
这一页也加入了providers
...
import { CommonService } from './service/common/common.service';
@NgModule({
declarations: [
...
],
imports: [
...
],
providers: [
...
CommonService
],
bootstrap: [AppComponent]
})
export class AppModule { }
LoginComponent
在需要使用请求的组件中引入CommonService服务,此时也没有报错
import { Component, OnInit } from '@angular/core';
import { CommonService } from 'src/app/service/common/common.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
constructor(private common: CommonService) { }
ngOnInit(): void {
}
}
问题复现:
正常的 "ng serve -o" 启动Angular项目,也正常启动了,但是进入LoginComponent组件页面后,显示不出页面,并且控制台报错
core.mjs:6485
ERROR Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[CommonService -> HttpClient -> HttpClient -> HttpClient]:
NullInjectorError: No provider for HttpClient!
NullInjectorError: R3InjectorError(AppModule)[CommonService -> HttpClient -> HttpClient -> HttpClient]:
NullInjectorError: No provider for HttpClient!
at NullInjector.get (core.mjs:11120:1)
at R3Injector.get (core.mjs:11287:1)
at R3Injector.get (core.mjs:11287:1)
at R3Injector.get (core.mjs:11287:1)
at injectInjectorOnly (core.mjs:4765:1)
at Module.ɵɵinject (core.mjs:4769:1)
at Object.CommonService_Factory [as factory] (common.service.ts:7:27)
at R3Injector.hydrate (core.mjs:11457:1)
at R3Injector.get (core.mjs:11276:1)
at NgModuleRef.get (core.mjs:21832:1)
at resolvePromise (zone.js:1211:1)
at resolvePromise (zone.js:1165:1)
at zone.js:1278:1
at _ZoneDelegate.invokeTask (zone.js:406:1)
at Object.onInvokeTask (core.mjs:25535:1)
at _ZoneDelegate.invokeTask (zone.js:405:1)
at Zone.runTask (zone.js:178:1)
at drainMicroTaskQueue (zone.js:585:1)
解决办法:
在“app.module.ts”文件中加入
,
imports: [
HttpClientModule
],
总结:
太马虎了!竟然忘记导入“HttpClientModule”,查了半天bug!!!
参考: