【问题标题】:What is the proper way to inject a service in Angular 8?在 Angular 8 中注入服务的正确方法是什么?
【发布时间】:2020-01-21 18:25:17
【问题描述】:

我正在尝试向我的主要“应用程序”组件注入服务。但它给出了一个错误(截图附在下面)

constructor(private newsApi: NewsApiService) {}

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

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

@注入

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 在 provider 中添加服务以访问任何地方

提供者:[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) {}
}

【问题讨论】:

  • 请出示app.module.ts的内容
  • 如果使用providedIn: 'root',则不需要将此服务添加到providers数组中。你是在app.module.ts 中导入HttpClientModule 吗?如果你是,你的代码应该可以工作stackblitz.com/edit/angular-d9xt1b
  • 我也编辑并添加了我的 app.module.ts 文件
  • 您是否尝试过杀死ng serve 进程并重新启动它?如果没有@Inject,我看不出您的代码无法运行的任何原因
  • 别担心,反正现在你已经找到答案了。这也是我在添加新代码文件时必须不时做的事情。

标签: javascript angular angular-services angular8


【解决方案1】:

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

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

1.) 使用 @Injectable() 装饰服务,例如 @Injectable() 导出类 SampleService{ 构造函数(){ } }

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

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

据我看到您的屏幕截图,这不是在注入问题的情况下引发的 staticInjector 错误。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

      What is the difference between @Inject and @Injectable in Angular 2 typescript

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-12-20
        • 2014-06-14
        • 2019-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-06
        • 2016-04-20
        相关资源
        最近更新 更多