'Property' serviceData 'does not exist in type' GeoService '.' Typescript Angular2

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class GeoService {
    constructor(private http: Http) { }

    private extractData(res : any){
        if(res.status < 200 || res.status >=300){
            throw new Error('Bad response sttus:' + res.status);
        }
        this.serviceData = (res.json());
        return this.serviceData || {};
    }

    loaddata(term: string): Observable<any> {
     return this.http.get('http://maps.google.com/maps/api/geocode/json?address=' + term + 'CA&sensor=false')
      .map(this.extractData);
  }
}

Why does he say that the 'Property' serviceData 'does not exist in the GeoService type?

+4
source share
2 answers

Well, this is not so, when you are extractDatatrying to turn to your function this.serviceData, you have not reported this to your service anywhere.

Try:

private extractData(res : any){
    if(res.status < 200 || res.status >=300){
        throw new Error('Bad response sttus:' + res.status);
    }
    let serviceData = res.json(); // declare here!
    return serviceData || {};
}

Another option is that you actually declare serviceData in your service, then you can use it thisin your function.

export class GeoService {
   private serviceData;
   ....

// and then use  this:
private extractData(res : any){
    if(res.status < 200 || res.status >=300){
        throw new Error('Bad response sttus:' + res.status);
    }
    this.serviceData = (res.json());
    return this.serviceData || {};
}

}

, , , OnInit :

data; // declare a variable where you want to store the data

constructor(private geoService: GeoService)  {
   this.geoService.loaddata() 
     .subscribe(data => {
       this.data = data;
       console.log(this.data); // your values here!
     });
}

OnInit.

+3
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class GeoService {
    public serviceData:any;
    constructor(private http: Http) { }

    private extractData(res : any){
        if(res.status < 200 || res.status >=300){
            throw new Error('Bad response sttus:' + res.status);
        }
        this.serviceData = (res.json());
        return this.serviceData || {};
    }

    loaddata(term: string): Observable<any> {
     return this.http.get('http://maps.google.com/maps/api/geocode/json?address=' + term + 'CA&sensor=false')
      .map(this.extractData);
  }
}
+1

Source: https://habr.com/ru/post/1667756/


All Articles