Angular v4.2.4中DataService无法解析参数问题求助
Fixing "Can't resolve all parameters for DataService" in Angular 4.2.4
Hey there! Let's break down what's causing this error and how to fix it quickly.
The root issue here is a missing decorator syntax in your DataService class. Angular relies on the @Injectable() decorator (note the @ symbol) to recognize that a class needs dependency injection support. Without it, Angular can't properly resolve the HttpClient parameter in your service's constructor.
Here's the fix for your dataService.ts file:
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import 'rxjs/add/operator/map'; import { Product } from './product'; // Add the @ symbol before Injectable() @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; }) } }
Why this works:
- The
@Injectable()decorator tells Angular that this class has dependencies that need to be injected (in this case,HttpClient). Without the@symbol, it's just a regular function call that doesn't register the service with Angular's dependency injection system. - Your
AppModuleis already set up correctly: you've importedHttpClientModuleand addedDataServiceto theprovidersarray, so once you fix the decorator, the dependency resolution should work as expected.
After making this change, restart your Angular dev server and try loading the data again. The error should be resolved, and your component should be able to fetch data from your local API just like it does in Postman.
内容的提问来源于stack exchange,提问作者AllramEst
相关产品推荐
相关产品推荐

