我正在使用Angular v.4.2.4。当我尝试从API获取数据时,我得到一个我似乎无法找到的错误。 API在我自己的机器上,并在邮递员中返回数据。我得到的错误是:
Can't resolve all parameters for DataService
以下是我认为有助于查找错误的文件:
app.module
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { ProductComponent } from './shop/product.component';
import { DataService } from './shared/dataService';
@NgModule({
declarations: [
AppComponent,
ProductComponent
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [DataService],
bootstrap: [AppComponent]
})
export class AppModule { }
的DataService
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import { Product } from './product';
Injectable()
export class DataService {
constructor(private http: HttpClient) { }
public products: Product[] = [];
loadProducts(): Observable<boolean>{
return this.http.get('/api/products')
.map((data: any[]) => {
this.products = data;
return true;
})
}
}
product.component
import { Component, OnInit } from "@angular/core";
import { DataService } from '../shared/dataService';
import { Product } from '../shared/product';
@Component({
selector: "product-list",
templateUrl: "productList.component.html",
styleUrls: []
})
export class ProductComponent implements OnInit {
constructor(private data: DataService) { }
public products: Product[] = [];
ngOnInit(): void {
this.data.loadProducts()
.subscribe(success => {
if (success) {
this.products = this.data.products;
}
});
}
}
告诉我你是否想看到其他任何东西。感谢您的帮助。
答案 0 :(得分:3)
您需要在“产品”API中提供一些数据值作为参数 在您的产品组件中。
this.data.loadProducts({'url': '/api/products', 'data':{
'x': ''
}}).subscribe(success =>{
console.log(success);
})
loadProducts(data): Observable<boolean>{
return this.http.get(data.url, data.data)
.map((data: any[]) => {
this.products = data;
return true;
})
}