I'm trying to get JSON data kept in the local system using Angular2 http.
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { General } from './general';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class GeneralService {
// #docregion endpoint
private statusUrl = './jsondata'; // URL to web API
// #enddocregion endpoint
// #docregion ctor
constructor (private http: Http) {}
// #enddocregion ctor
// #docregion methods, error-handling, http-get
getStatus (): Observable<General[]> {
return this.http.get(this.statusUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
private handleError (error: Response | any) {
// In a real world app, we 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);
}
}
I'm getting error- Type observable<{}> is not assignable to type 'Observable'.Type '{}' is not assignable to type 'General[]'. Property length is missing in type'{}'
Here General is a class name. Im using rxjs-5.0. I'm following Angular.io Tour of heroes and making my own project. Any help on this?
I changed my imports from
import { Observable } from 'rxjs/Observable';
to
import { Observable } from 'rxjs';
And it all worked
The problem is that you are telling to observable to get a list of Genral while you are getting an object.
getStatus (): Observable<General[]>
If you are not accepting an array then you should do like this
getStatus (): Observable<General>
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