angular - Kiểu không thể gán cho kiểu providedIn. Thuộc tính ProvidedIn bị thiếu
Tôi đang cố gắng tạo một dịch vụ với sự giúp đỡ của hướng dẫn Angular https://angular.io/guide/http
Tôi đang sử dụng Angular 7.0.7.
Dịch vụ sẽ lấy dữ liệu json từ một số 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);
}
}
Tôi đang thấy một đường gợn sóng dưới @Injectable() với tiêu đề của câu hỏi này. Tại sao lại xảy ra điều đó, và làm thế nào để tôi giải quyết nó?
Tôi có một thành phần sẽ sử dụng dịch vụ này:
import { ProductListService } from '../services/productList.service';
@Component({
selector: 'app-productlist',
templateUrl: './productlist.component.html',
styleUrls: ['./productlist.component.css'],
providers: [ProductListService]
})
Câu trả lời #1
Bạn đã quên thêm dấu ngoặc cho @Injectable() decorator
@Injectable()
export class ProductListService {
constructor(private http: HttpClient) {
}
Câu trả lời số 2
@Injectable của bạn không đúng. Thêm thuộc tính providedIn tham chiếu đến component của bạn sẽ sử dụng service:
@Injectable({
providedIn: 'app-productlist',
})
export class ProductListService {
constructor(private http: HttpClient) {
}
Một giải pháp khác là chỉ cần sử dụng decorator như vậy: @Injectable(), và khai báo service của bạn trong file app.module.ts của bạn, như một provider
@Injectable()
export class ProductListService {
constructor(private http: HttpClient) {
}
