【发布时间】: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