Vishnu
Vishnu

Reputation: 475

this does not access http response object:property does not exist on type Object

I have response object i just assigned to "this" object.

private data: Object = {};

this.http.post('url', { })
    .subscribe(
        res => {
            console.log(res);
            this.data = res;

            if(this.data.datacentersinfo.length) {}

...

If I access datacentersinfo object it saying property datacentersinfo does not exist on type Object. Because of this error, I am not able to generate the dist folder.

Upvotes: 2

Views: 1495

Answers (3)

Pranay Rana
Pranay Rana

Reputation: 176896

i suggest you make use of strongly type object and do as below

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, 
             Response, ResponseContentType } from '@angular/http';

GetAllCriteria(): Observable<Array<ClassName>> {
    let headers = new Headers({
        'Content-Type': 'application/json'
    });
    let options = new RequestOptions({ headers: headers });
    return this._http.get(this.apiUrl + "/GetAllCriteria",
                       options).subscribe(response => response.json());
}

Upvotes: 2

user4676340
user4676340

Reputation:

You have several solutions :

1 - type your data to any and don't instanciate it :

private data: any;

2 - change your condition :

if(this.data && this.data.datacentersinfo && this.data.datacentersinfo.length) {}

This should resolve your issue.

Upvotes: 3

Wesley Coetzee
Wesley Coetzee

Reputation: 4838

I'll post both ways to do this. First the old way (which looks like how you're trying to do it), then the preferred way using HTTP Client

Old HTTP

private data: Object = {};
this.http.post('url', { })
    .map((res: Response) => res.json())
    .subscribe((res:any) => {
        console.log(res);
        this.data = res;
        if(this.data.datacentersinfo.length) {}
});

HTTP Client

private data: Object = {};
    this.http.post<any>('url', { })            
        .subscribe((res:any) => {
            console.log(res);
            this.data = res;
            if(this.data.datacentersinfo.length) {}
    });

I'm not doing this the best way it should be done, you should create a service component that handles the HTTP request, then call that service from the component and subscribe to it's response there.

Upvotes: 1

Related Questions