在 Angular 8 中注入服务的正确方法是什么?

What is the proper way to inject a service in Angular 8?

我正在尝试向我的主要 "App" 组件注入服务。但是它给出了一个错误(下面附上截图)

constructor(private newsApi: NewsApiService) {}

使用上述代码导入服务时出现此错误

我用谷歌搜索并找到了解决方案。正在添加

@Inject

constructor(@Inject(NewsApiService) newsApi: NewsApiService) {}

但是在Angular.io的文档中,它显示了我使用的第一种方式。我想知道我是否遗漏了什么?

我的 NewsApiService 有 HttpClient 并且它发送 HTTP 请求。该服务中编写的函数都是异步的,因为它们需要发送请求和获取数据。

NewsApiService.service.ts

import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class NewsApiService {
  apiKey = '--My_API_Key_Goes_here--';

  constructor(private http: HttpClient) {
  }

  initSources() {
    return this.http.get('https://newsapi.org/v2/sources?language=en&apiKey=' + this.apiKey);
  }

  initArticles() {
    return this.http.get('https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=' + this.apiKey);
  }

  getArticlesByID(source: string) {
    return this.http.get('https://newsapi.org/v2/top-headlines?sources=' + source + '&apiKey=' + this.apiKey);
  }
}

App.module.ts 在提供者中添加服务以访问任何地方

providers: [NewsApiService],

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

import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {
  MatButtonModule,
  MatCardModule,
  MatIconModule,
  MatListModule,
  MatMenuModule,
  MatSidenavModule,
  MatToolbarModule
} from '@angular/material';

import { AppComponent } from './app.component';
import {NewsApiService} from './news-api.service';
import {FormsModule} from '@angular/forms';


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    BrowserAnimationsModule,
    HttpClientModule,
    MatButtonModule,
    MatMenuModule,
    MatCardModule,
    MatToolbarModule,
    MatIconModule,
    MatSidenavModule,
    MatListModule,
  ],
  providers: [NewsApiService],
  bootstrap: [AppComponent]
})
export class AppModule { }

App.component.ts

import {Component, Inject, OnInit} from '@angular/core';
import {NewsApiService} from './news-api.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent{
  mArticles: Array<any>;
  mSources: Array<any>;

  constructor(@Inject(NewsApiService) newsApi: NewsApiService) {}
}

使用 @Injectable() 装饰器,它可以将 class 注入特定的 class 或组件。

基本上以下三个步骤使服务消费

1.) 用@Injectable() 装饰服务 @Injectable() 导出 class 样本服务{ 构造函数(){ } }

2.) 在模块文件@NgModule装饰器的providers数组中添加服务引用

3.)// 消费服务 构造函数(私有样本服务:样本服务){}

据我所见,这不是注入问题时抛出的 staticInjector 错误。

有时您必须重新启动 ng serve 才能在新文件中获取更改。我偶尔会在注入器依赖项中遇到这种情况,我在其中添加了一个新代码文件作为另一个 component/service.

中的依赖项

如果您想显式使用注入与可注入,请查看已经回答的post: