Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type observable<{}> is not assignable to any type:Property length is missing in type{} in Typescript

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?

like image 777
Protagonist Avatar asked Nov 07 '16 15:11

Protagonist


2 Answers

I changed my imports from
import { Observable } from 'rxjs/Observable';
to
import { Observable } from 'rxjs';
And it all worked

like image 200
Norman Pilusa Avatar answered Nov 11 '22 01:11

Norman Pilusa


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> 
like image 4
Jorawar Singh Avatar answered Nov 11 '22 02:11

Jorawar Singh