I am trying to create a service with the help of Angular's tutorial https://angular.io/guide/http
I'm using Angular 7.0.7
.
The service would get json data from some url:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable
export class ProductListService {
constructor(private http: HttpClient) {
}
productListUrl: string = "https://blahblah.com/products";
getProductList() {
return this.http.get(this.productListUrl);
}
}
I am getting a squiggly line under @Injectable()
with the title of this question. Why is that happening, and how do I resolve it?
I have a component which will be using this service:
import { ProductListService } from '../services/productList.service';
@Component({
selector: 'app-productlist',
templateUrl: './productlist.component.html',
styleUrls: ['./productlist.component.css'],
providers: [ProductListService]
})
Your @Injectable
is not correct. Add the providedIn
property which reference your component which will use the service:
@Injectable({
providedIn: 'app-productlist',
})
export class ProductListService {
constructor(private http: HttpClient) {
}
Another solution is to just use the decorator like that: @Injectable()
, and to declare your service in your app.module.ts
file, as provider
@Injectable()
export class ProductListService {
constructor(private http: HttpClient) {
}