首页 > 解决方案 > Angular向构造函数添加服务导致没有内容显示

问题描述

每当我尝试在该组件的某些组件的构造函数内容中添加服务时,都不会显示。

我的简单服务如下所示:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { News } from 'src/app/interfaces/news';
    
@Injectable(
{providedIn: 'root'}
) 
export class NewsService {  
     public newsUrl = 'some url';
     
    constructor(private http: HttpClient) {    }
     
     public getNews(): Observable<News[]> {
         console.log(this.newsUrl);
         return this.http.get<News[]>(this.newsUrl+'/news/all');   
    }
}

我什至没有使用它,只是像这样传入构造函数:

导出类 TestComponent ...

构造函数(私人新闻服务:新闻服务){}

标签: angular

解决方案


确保你在你的模块中导入:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // import HttpClientModule after BrowserModule.
    HttpClientModule,
  ],
  declarations: [
    AppComponent,
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {}

文档


推荐阅读