在Angular 2(TypeScript)下面的代码给出了3以下的错误,如何解决它们.请建议.
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { NgModule, Component } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule, Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from "rxjs/Observable";
@Component({
selector: 'http-client',
template: `All Products
-
{{product.title}}
`})
class AppComponent {
products: Array = [];
theDataSource: Observable;
constructor(private http: Http) {
this.theDataSource = this.http.get('api/products/')
.map(res => res.json());
}
ngOnInit() {
// Get the data from the server
this.theDataSource.subscribe(
data => {
if (Array.isArray(data)) {
this.products = data;
} else {
this.products.push(data);
}
},
err =>
console.log("Can't get products. Error code: %s, URL: %s ", err.status, err.url),
() => console.log('Product(s) are retrieved')
);
}
}
@NgModule({
imports: [BrowserModule,
HttpModule],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
class AppModule { }
platformBrowserDynamic().bootstrapModule(AppModule);
错误是,
TS2314泛型类型'Observable'需要1个类型的参数.
TS7006参数'data'隐式具有'any'类型.
TS7006参数'err'隐式具有'any'类型.
Günter Zöchb.. 35
theDataSource: Observable;
哪里any
可以(或应该如果可能)是一个更具体的类型,它匹配它应该发出的值的类型.
theDataSource: Observable;
哪里any
可以(或应该如果可能)是一个更具体的类型,它匹配它应该发出的值的类型.
如果你查看Angular Http模块的源代码,你可以找到Http类的方法请求
https://github.com/angular/angular/blob/2.4.1/modules/%40angular/http/src/http.ts#L111
所有其他方法(获取,发布等)包装此请求.您还可以看到该请求返回一个具有Response类通用的Observable.响应类是Http模块的一部分,因此您的代码可以修改为:
import { HttpModule, Http, Response } from '@angular/http'; ... theDataSource: Observable;
或者,如果您不需要这种强大的典型,您可以传递任何作为泛型的参数
theDataSource: Observable;
但在我看来 - 强大的典型是更好的选择.