Vladimir_314159
Vladimir_314159

Reputation: 1677

angular processing a json object compiling but throwing a error

I have the following component in a angular6 project.

export class BoxdataComponent implements OnInit {
  numberOnSite: Object;
  number: number;
  numberClicks: Object;
  constructor(private _pullAnalyticsService: PullanaliticsService) {}

  ngOnInit() {
    timer(0, 5000).pipe(
      switchMap( _ => this._pullAnalyticsService.httpGetAsync()
    )).pipe(
      map(ret => {
        console.log(ret.ListOfData[0]); // ListOfData[0]);
        console.log(ret.ListOfData[1]);
        this.numberOnSite = ret.ListOfData[0];
        this.numberClicks = ret.ListOfData[1];
      })
    ).subscribe();
  }

}

where the httpGetAsync() is defined in a service as.

  httpGetAsync() {
      return this.httpClient.get(this.theUrl);
  }

Now this is working fine I see the correct data in the console and numberOnSite and numberClicks are the correct value. But I am getting the error:

ERROR in src/app/boxdata/boxdata.component.ts(22,25): error TS2339: Property 'ListOfData' does not exist on type 'Object'.
src/app/boxdata/boxdata.component.ts(23,25): error TS2339: Property 'ListOfData' does not exist on type 'Object'.
src/app/boxdata/boxdata.component.ts(24,33): error TS2339: Property 'ListOfData' does not exist on type 'Object'.
src/app/boxdata/boxdata.component.ts(25,33): error TS2339: Property 'ListOfData' does not exist on type 'Object'.

Note: ret is a json object.

Defined as:

{"ListOfData": [  4467 , 4065 ]}

These errors are thrown after the project successfully refreshes. Also if I stop the project with ctrl-C and run ng serve the project will no longer "compile." However if I remove the problematic lines, run ng serve then change them back again it works. Why is the project doing this? I am on vs code if that has anything to do with it. Thx.

Upvotes: 0

Views: 39

Answers (2)

user184994
user184994

Reputation: 18281

Change the pipe line to

map((ret:any) => {

It is a compilation error being caused by type checking, as ret is being treated as type Object, which does not have a ListOfData property.

By typing ret:any, we're removing the type checking, and saying it may have any properties

Upvotes: 1

Karnan Muthukumar
Karnan Muthukumar

Reputation: 1863

Please remove "Object" declared variable let's declare like this

numberOnSite:any; //if your variable array use like this any[]=[]: numberClicks:any;

Upvotes: 0

Related Questions