在这里,我想显示客户列表,我正在该类中编写一个服务类,编写一个函数 getCustomer()
data.service.ts
// @Injectable() // comment to this line in service if we are inject service in component
export class DataService {
constructor(public http: Http) { }
getCustomers(): Promise<ICustomer[]> {
return this.http.get(this.customersBaseUrl)
.toPromise()
.then(response => response.json().data as ICustomer[])
.catch(this.handleError);
}
}
在 customer.component.ts 中调用getCustomer()
constructor(@Inject(DataService) private dataService: DataService) { }
ngOnInit() {
this.title;
this.filterText = 'Filter Customers:';
this.dataService.getCustomers().then(customers => this.customers = customers.slice(1, 5));
}
app.module.ts
import { HttpModule } from '@angular/http';
@NgModule({
declarations: [
AppComponent,
CustomersComponent,
],
imports: [
HttpModule,
app_routing,
..
],
providers: [
DataService,
],
bootstrap: [AppComponent,NavbarComponent]
})
如果我在任何方面都错了,请给我建议。我是打字稿的新手,所以我对此没有太多的想法。谢谢提前
答案 0 :(得分:2)
只需更改您的代码,如下所示。
ngOnInit() {
this.title;
this.filterText = 'Filter Customers:';
this.dataService.getCustomers().subscribe(customers => this.customers = customers.slice(1, 5));
}
在data.service.ts
中getCustomers(): Observable<ICustomer[][]> {
return this.http.get(this.customersBaseUrl)
.map((response: Response) => <ICustomer[]>response.json())
.do(data => console.log("All: " + JSON.stringify(data)))
.catch(this.handleError);
}
private handleError(error: Response) {
console.error(error);
return Observable.throw(error.json().error || 'Server error');
}
答案 1 :(得分:0)
对DataService中的@Injectable()发表评论。如果我们在组件中注入服务,则无需注入服务
//@Injectable()
export class DataService {
constructor(public http: Http) { }
getCustomers(): Promise<ICustomer[]> {
return this.http.get(this.customersBaseUrl)
.toPromise()
.then(response => response.json().data as ICustomer[])
.catch(this.handleError);
}
}
答案 2 :(得分:-2)
如果这是与您的错误有关的代码,那么您的错误来自get
来电。这意味着,Angulars不了解您的HTTP服务。你有没有正确地实现它?