Below Angular 2 (TypeScript) code gave me below 3 error, how to resolve them. please suggest.
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: `<h1>All Products</h1>
<ul>
<li *ngFor="let product of products">
{{product.title}}
</li>
</ul>
`})
class AppComponent {
products: Array<string> = [];
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);
Error are,
theDataSource: Observable<any>;
where any
can (or should be if possible) be a more concrete type that matches the type of the values it is supposed to emit.
If you look in source of Angular Http module you can find method request of Http class
https://github.com/angular/angular/blob/2.4.1/modules/%40angular/http/src/http.ts#L111
All other methods (get, post, etc. ) wrap this request. Also you can see that request returns an Observable with generic of Response class. Response class is a part of Http module, so your code can be modified to this:
import { HttpModule, Http, Response } from '@angular/http';
...
theDataSource: Observable<Response>;
Or, if you do not need this strong typification you can pass any as parameter of generic
theDataSource: Observable<any>;
But in my opinion - strong typification is better choice.
1) theDataSource: Observable;
-> theDataSource: Observable<any>;
2/3) you can add "noImplicitAny": false
to your tsconfig.json
or change data =>
and err =>
with (data: any) =>
and (err: any) =>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With