如何修复错误错误:未捕获(承诺):NullInjectorError:StaticInjectorError(AppModule)[HomeComponent-> HttpHeaders]

时间:2019-11-07 09:07:23

标签: angular

使用GET方法从API调用获取信息时,我遇到了这样的问题

  

core.js:6014错误错误:未捕获(已承诺):NullInjectorError:StaticInjectorError(AppModule)[HomeComponent-> HttpHeaders]:     StaticInjectorError(平台:核心)[HomeComponent-> HttpHeaders]:       NullInjectorError:HttpHeaders没有提供者!   NullInjectorError:StaticInjectorError(AppModule)[HomeComponent-> HttpHeaders]:     StaticInjectorError(平台:核心)[HomeComponent-> HttpHeaders]:       NullInjectorError:HttpHeaders没有提供者!       在NullInjector.get(core.js:855)       在resolveToken(core.js:17513)       在tryResolveToken(core.js:17439)       在StaticInjector.get(core.js:17265)       在resolveToken(core.js:17513)       在tryResolveToken(core.js:17439)       在StaticInjector.get(core.js:17265)       在resolveNgModuleDep(core.js:30392)       在NgModuleRef_.get(core.js:31577)       在resolveDep(core.js:32142)       在resolvePromise(zone-evergreen.js:797)       在resolvePromise(zone-evergreen.js:754)       在zone-evergreen.js:858       在ZoneDelegate.invokeTask(zone-evergreen.js:391)       在Object.onInvokeTask(core.js:39679)       在ZoneDelegate.invokeTask(zone-evergreen.js:390)       在Zone.runTask(zone-evergreen.js:168)       在排水微任务队列(zone-evergreen.js:559)

代码:

return this.http
      .get('http://localhost/advanced/frontend/web/leftside-menu/get-left-menu')
      .subscribe(
        (result) => { }
      );

3 个答案:

答案 0 :(得分:1)

您是否已在app.module.ts中导入HttpClientModule?如果没有,则输入此行代码。

import { HttpClientModule } from '@angular/common/http'; 

@NgModule({  
            imports: [ BrowserModule, FormsModule, HttpClientModule ],
            declarations: [ ]
           })

答案 1 :(得分:1)

在app.module.ts中导入HttpClientModule

import { HttpClientModule } from '@angular/common/http'; 

@NgModule({  
   imports: [ BrowserModule, FormsModule, HttpClientModule ],
   declarations: [ ]
})

在您的service.ts文件中导入HttpClient

import { MyModel } from './my-model.model'
export class UserMaterService {
  list: MyModel[];
  constructor(private http: HttpClient) { }
  this.http.get(url).toPromise().then(res => this.stringData = res as listData[]);
}

答案 2 :(得分:0)

此外,如果出现这种情况,请检查您在任何组件的构造函数中编写的内容。

例如,我出于某种原因在那里放置了另一个组件,所以这是错误的 当我删除它时,它开始工作

  constructor(
    private chatRoomsService: ChatRoomService,
    private router: Router,
    private route: ActivatedRoute
    private messageComponent: MessageComponent //it has to be erased
  ) { }