我正在Angular中构建一个小型玩具应用程序,其中包含以下类别({1}}和ProductDetailComponent
。该服务包含一个为产品发出http GET请求的方法。组件显示产品的详细信息,并使用该服务检索产品信息。将ProductService
添加到应用程序(以及其中的服务)之后,我的组件测试失败了,说"错误:没有Http的提供者!"。
如果我导入HttpModule
,测试会再次通过。但是,我首先感到困惑的是它首先需要HttpModule
,因为这是HttpModule
依赖项,我使用提供程序嘲笑ProductService
。< / p>
所以我的问题很简单,为什么测试告诉我当被测试的类不使用它时我需要这种依赖?
产品detail.component.ts
ProductService
product.service.ts
import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Params} from "@angular/router";
import {ProductService} from "../product.service";
import {Product} from "../product";
import 'rxjs/add/operator/switchMap';
@Component({
selector: 'app-product-detail',
templateUrl: './product-detail.component.html',
styleUrls: ['./product-detail.component.css'],
providers: [ProductService]
})
export class ProductDetailComponent implements OnInit {
product: Product;
constructor(
private productService: ProductService,
private route: ActivatedRoute,
) { }
ngOnInit() {
this.route.params
.switchMap((params: Params) => this.productService.getProduct(+params['id']))
.subscribe(product => this.product = product);
}
}
产品detail.component.spec.ts:
import {Injectable} from "@angular/core";
import {Product} from "./product";
import {Http} from "@angular/http";
import "rxjs/add/operator/toPromise";
@Injectable()
export class ProductService {
private products: Product[];
constructor(private http: Http) { }
getProducts(): Promise<Product[]> {
return this.http
.get('/api/products/')
.toPromise()
.then(response => response.json() as Product[])
.catch(error => {
console.error('An error occurred', error);
return Promise.reject(error.message || error)
});
}
getProduct(id: number): Promise<Product> {
return this.http
.get(`/api/products/${id}`)
.toPromise()
.then(response => response.json() as Product)
.catch(error => {
console.error('An error occurred', error);
return Promise.reject(error.message || error)
});
}
}
答案 0 :(得分:0)
尝试:
HttpModule
到您的NgModule
NgModule
或ProductDetailComponent
例如: product.module.ts
import { HttpModule } from '@angular/http';
import { ProductDetailComponent } from './product-detail.component';
import { ProductService } from 'product.service';
@NgModule({
imports: [
HttpModule,
NgbModule.forRoot(),
],
declarations: [
ProductDetailComponent
],
providers: [
ProductService
],
})
export class ProductModule { }
答案 1 :(得分:0)
在您的模块中,您必须将<link type="text/css" media="screen" rel="stylesheet" href="/css/main.css">
<link type="text/css" media="print" rel="stylesheet" href="/css/print.css">
提供程序添加到您的提供程序属性:
提供者:[ProductService]