在这里我创建了两个 ts 文件,一个是服务,另一个是服务中的常规,我实现了一些服务并在通用 ts 文件中调用,同时我的页面正在加载其贯穿错误,如 NoProviderError.BaseError [作为构造函数]
服务网
@Component({
templateUrl: "../../template/customer/customer.html",
providers: [CustomerService]
})
Url = "http://localhost:54873/Api/Home/GetEmp"
public constructor(private _http: Http) {
}
getEmpData() {
debugger;
return this._http.get(this.Url).map(this.extractData).catch(this.handleError);
}
组件.ts
@Component({
templateUrl: "../../template/customer/customer.html",
providers: [CustomerService]
})
@Injectable()
export class CustomerComponent {
Url = "http://localhost:54873/Api/Home/GetEmp"
getfun: string;
constructor(private _HttpService: CustomerService) { }
getData() {
return this._HttpService.getEmpData().subscribe(data => this.getfun = JSON.stringify(data), error => alert('This is error...'),
() => console.log());
}
你不能在
service.ts 文件中有@Component,它应该如下所示,
@Injectable()
export class CustomerService {
public constructor(private _http: Http) {
}
getEmpData(): Observable<Employee[]> {
debugger;
return this._http.get(this.Url).map(this.extractData).catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
// this.Employees = res.json
return body.data || {};
}
private handleError(error: Response | any) {
// In a real world app, you might use a remote logging infrastructure
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}