我正在尝试向我的主要“App”组件注入(inject)服务。但它给出了一个错误(下面附上截图)
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 在provider中添加服务,随处访问
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) {}
}
最佳答案
有时您必须重新启动 ng serve
才能在新文件中获取更改。我偶尔会在注入(inject)器依赖项中遇到这种情况,我添加了一个新的代码文件作为另一个组件/服务的依赖项。
关于javascript - 在 Angular 8 中注入(inject)服务的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58032688/