I am using Angular v.4.2.4. When I try to get data from an API I get an error I cant seem to find. The API is on my own machine and is returning data as it should in postman. The error I am getting is:
Can't resolve all parameters for DataService
Here are my files I thought would help to find the error:
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;
}
});
}
}
Tell me if you want to see anything else. Thanks for all the help.
you need to provide some data value as parameter in your 'product' api in your product component.
this.data.loadProducts({'url': '/api/products', 'data':{
'x': ''
}}).subscribe(success =>{
console.log(success);
})
in your dataService
loadProducts(data): Observable<boolean>{
return this.http.get(data.url, data.data)
.map((data: any[]) => {
this.products = data;
return true;
})
}